package com.gem.media.splash.base.crash;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Process;
import android.text.TextUtils;

import com.ads.cal.notes.BaseApplication;
import com.or.ange.dot.SystemUtils;
import com.or.ange.dot.utils.DeviceIDUtils;
import com.or.ange.dot.utils.LLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;


public class CrashReportRunnable implements Runnable {

    private static final String TAG = "ReportRunnable";
    private JSONObject common;
    private String imei;
    private String androidId;
    private String appId;
    private String country;
    private String language;
    private String countryCode;
    private String simOperatorMcc;
    private volatile boolean isReporting = false;

    private String reportUrl;

    private Event event;

    public CrashReportRunnable() {
        Context context = BaseApplication.getApplication();
        try {
            this.imei = DeviceIDUtils.getImei(context);
            this.androidId = SystemUtils.getAndroidId(context);
            this.country = Locale.getDefault().getCountry();
            this.language = Locale.getDefault().getLanguage();
        } catch (Exception e2) {
        }
        try {
            this.countryCode = CountryUtil.getCountryCode(context);
            this.simOperatorMcc = CountryUtil.getSimOperatorMcc(context);
        } catch (Exception e3) {
        }
    }

    public void setEvent(Event event) {
        this.event = event;
    }

    public void setUrl(String reportUrl) {
        this.reportUrl = reportUrl;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    @Override
    public void run() {
        List<Event> events = new ArrayList<>();
        if (event != null) {
            events.add(event);
        }
        if (events.isEmpty()) {
            LLog.d(TAG, "events is empty, not report.");
            return;
        }

        boolean success = false;
        this.isReporting = true;
        BufferedReader br = null;
        try {
            JSONObject object = getTrackerJSONObject(events);
            HashMap<String, String> heads = new HashMap<>();
            heads.put("Content-Type", "application/json");
            HttpURLConnection conn = Http.post(reportUrl, heads, null, object.toString());
            if (conn != null) {
                success = conn.getResponseCode() == 200;
                if (success) {
                    StringBuilder rest = new StringBuilder();
                    br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                    while (true) {
                        String line = br.readLine();
                        if (null == line) {
                            break;
                        }
                        rest.append(line);
                    }
                    success = new JSONObject(AESEncryptUtil.decrypt2(rest.toString())).optInt("a") == 0;
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            if (success) {
                LLog.d(TAG, "track after success ");
            } else {
                if (conn == null) {
                    LLog.d(TAG, "track fail. null" );
                } else {
                    LLog.d(TAG, "track fail. code = " + conn.getResponseCode());
                }
            }
            this.isReporting = false;
        } catch (Exception e) {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e22) {
                    this.isReporting = false;
                }
            }
            if (!success) {
            }
            this.isReporting = false;
        } catch (Throwable th) {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e23) {
                    e23.printStackTrace();
                    throw th;
                }
            }
            if (!success) {
            }
            this.isReporting = false;
            throw th;
        } finally {
            LLog.d(TAG, " Process.killProcess "+Process.myPid());
            Process.killProcess(Process.myPid());
        }
    }

    private JSONObject getTrackerJSONObject(List<Event> events) {
        JSONObject object = new JSONObject();
        try {
            object.put("cp", getCommonJSONObject());
            JSONArray array = new JSONArray();
            for (Event event : events) {
                array.put(getEventJSONObject(event));
            }
            object.put("e", array);
            object.put("n", "1");
        } catch (JSONException e) {
            LLog.d(TAG, e.toString());
        }
        return object;
    }

    @SuppressLint({"MissingPermission"})
    private JSONObject getCommonJSONObject() throws JSONException {
        Context context = BaseApplication.getApplication();
        if (this.common == null && null != context) {
            String pkgName = context.getPackageName();
            this.common = new JSONObject();
            this.common.put("ai", this.appId);
            this.common.put("i", this.imei);
            this.common.put("a_id", this.androidId);
            this.common.put("pk", pkgName);
            this.common.put("vc", getAppVersionCode());
            this.common.put("vn", getAppVersionName());
            this.common.put("ol", Build.VERSION.SDK_INT);
            this.common.put("ov", Build.VERSION.RELEASE);
            this.common.put("b", Build.BRAND);
            this.common.put("m", Build.MODEL);
            this.common.put("d", Build.DEVICE);
            this.common.put("bo", Build.BOARD);
            this.common.put("ft", Build.FINGERPRINT);
            this.common.put("hw", Build.HARDWARE);
            this.common.put("dy", Build.DISPLAY);
            this.common.put("id", Build.ID);
            this.common.put("pt", Build.PRODUCT);
            this.common.put("us", Build.USER);
            this.common.put("mf", Build.MANUFACTURER);
            this.common.put("cn", this.country);
            this.common.put("lag", this.language);
            this.common.put("coc", this.countryCode);
            this.common.put("som", this.simOperatorMcc);
            if (Build.VERSION.SDK_INT >= 26) {
                String serial = "";
                try {
                    serial = Build.getSerial();
                } catch (Exception e) {
                }
                this.common.put("sn", serial);
            }
        }
        return this.common;
    }

    private JSONObject getEventJSONObject(Event event) throws JSONException {
        JSONObject object = new JSONObject();
        object.put("ei", event.getEventId());
        if (!BaseApplication.getApplication().getPackageName().equals(event.getLabel())) {
            object.put("label", event.getLabel());
        }
        object.put("et", event.getTimestamp());
        if (!getAppVersionName().equals(event.getVersionName())) {
            object.put("vc", event.getVersionCode());
            object.put("vn", event.getVersionName());
        }
        if (!TextUtils.isEmpty(event.getParams())) {
            object.put("pm", new JSONObject(event.getParams()));
        }
        return object;
    }

    public boolean isReporting() {
        return this.isReporting;
    }

    private static String getAppVersionName() {
        try {
            Context context = BaseApplication.getApplication();
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            if (pi != null) {
                return pi.versionName;
            }
            return "error:version";
        } catch (Exception e) {
            e.printStackTrace();
            return "error:version";
        }
    }

    private String getAppVersionCode() {
        try {
            Context context = BaseApplication.getApplication();
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            if (pi != null) {
                return String.valueOf(pi.versionCode);
            }
            return "-1";
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }
    }
}
