package com.gh.common.util;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.gh.gamecenter.common.base.GlobalActivityManager;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.common.base.activity.BaseActivity;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.retrofit.BiResponse;
import com.gh.gamecenter.common.utils.SensorsBridge;
import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.core.utils.GsonUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.SentryHelper;
import com.gh.gamecenter.login.entity.IdCardEntity;
import com.gh.gamecenter.login.entity.UserInfoEntity;
import com.gh.gamecenter.provider.GhContentProvider;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gid.GidCallback;
import com.gh.gid.GidHelper;
import com.halo.assistant.HaloApp;
import com.lightgame.config.CommonDebug;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.schedulers.Schedulers;
import io.sentry.Sentry;
import io.sentry.android.core.SentryAndroid;
import kotlin.Pair;

/**
 * Created by LGT on 2016/6/15.
 * 数据收集工具类
 */
public class DataUtils {

    private DataUtils() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 初始化各种统计工具，仅在release build（非debug）模式启用统计
     */
    public static void init(final Application context, String channel) {
        if (CommonDebug.IS_DEBUG) {
            return;
        }

        // 初始化 Sentry 约占用 90ms，这里切换到子线程初始化
        AppExecutor.getIoExecutor().execute(() -> initSentry(context, channel));
    }

    private static void initSentry(Context context, String channel) {
        SentryAndroid.init(context, options -> {
            // Sentry 疯狂报 ANR (很大一部分还是莫名奇妙的 ANR)严重影响到其它闪退日志的收集
            // 这里将它局限到只有官网渠道的包才统计 ANR
            if ("GH_206".equals(channel) || "GH_BETA".equals(channel) || com.gh.gamecenter.common.BuildConfig.BUILD_TIME != 0) {
                options.setAnrEnabled(true);
                options.setAnrTimeoutIntervalMillis(6000);
            } else {
                options.setAnrEnabled(false);
            }

            options.setDebug(BuildConfig.DEBUG);
            options.setEnableAutoSessionTracking(true);
            options.setEnvironment(BuildConfig.FLAVOR);
            options.setEnableSystemEventBreadcrumbs(false);
            options.setDsn("https://6b1caf0d17c1408e8680f3f73ff80bd0@sentry.shanqu.cc/22");

            options.setBeforeSend((event, hint) -> {
                if (BuildConfig.DEBUG) {
                    return null;
                } else {
                    return event;
                }
            });

            options.setBeforeBreadcrumb(((breadcrumb, hint) -> {
                if ("ui.lifecycle".equals(breadcrumb.getCategory()) && "started".equals(breadcrumb.getData("state")) && GlobalActivityManager.INSTANCE.getCurrentActivity() instanceof BaseActivity) {
                    Pair<String, String> businessId = ((BaseActivity) GlobalActivityManager.INSTANCE.getCurrentActivity()).getBusinessId();
                    if (businessId != null) {
                        breadcrumb.setData("businessId1", businessId.component1());
                        breadcrumb.setData("businessId2", businessId.component2());
                    }
                }
                return breadcrumb;
            }));
        });

        Sentry.configureScope(scope -> {
            if (com.gh.gamecenter.common.BuildConfig.BUILD_TIME != 0L) {
                scope.setTag("alias", "内测版" + BuildConfig.VERSION_NAME);
            } else {
                scope.setTag("alias", "正式版" + BuildConfig.VERSION_NAME);
                scope.setTag("channel", channel);
            }
        });
    }

    public static void getGid() {
        GidHelper.getInstance().registerDevice(HaloApp.getInstance().getApplication(), new GidCallback() {
            @Override
            public void onSuccess(String gid) {
                Utils.log("Gid", gid);
                PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().getApplication()).edit().putString(Constants.DEVICE_KEY, gid).apply();

                String originalGid = HaloApp.getInstance().getGid();
                HaloApp.getInstance().setGid(gid);

                // gid 变更时上报 gid 变更日志
                if (!TextUtils.isEmpty(originalGid) && !originalGid.equals(gid)) {
                    NewFlatLogUtils.logGidChanged(originalGid, gid);
                }

                SensorsBridge.setGid(gid);

                // 避免重复调用
                if (!TextUtils.isEmpty(gid) && !gid.equals(originalGid)) {
                    GameSubstituteRepositoryHelper.updateSubstitutableGames();
                }

                getDeviceCertification(gid);

                // 避免初始化顺序问题导致 MetaUtil 一直持有空的 gid
                MetaUtil.INSTANCE.refreshMeta();

                ContentValues values = new ContentValues();
                values.put(GhContentProvider.KEY_GID, gid);
                values.put(GhContentProvider.KEY_ANDROID_ID, MetaUtil.getBase64EncodedAndroidId());
                try {
                    HaloApp.getInstance().getContentResolver().insert(Uri.parse("content://com.gh.gamecenter.provider/device"), values);
                } catch (Exception exception) {
                    SentryHelper.INSTANCE.onEvent("DEVICE_INSERT_ERROR", "exception_digest", exception.getLocalizedMessage());
                    exception.printStackTrace();
                }
            }

            @Override
            public void onFailure(String s) {
                MtaHelper.onEventWithBasicDeviceInfo("开发辅助", "GID 获取异常", s);
            }
        });
    }

    /**
     * 获取应用 gid 绑定的实名信息
     */
    @SuppressLint("CheckResult")
    public static void getDeviceCertification(String gid) {
        RetrofitManager.getInstance()
                .getApi()
                .getCertification()
                .subscribeOn(Schedulers.io())
                .subscribe(new BiResponse<UserInfoEntity>() {
                    @Override
                    public void onSuccess(UserInfoEntity data) {
                        SPUtils.setString(Constants.SP_DEVICE_CERTIFICATION_PREFIX + gid, GsonUtils.toJson(data));

                        ContentValues values = new ContentValues();
                        IdCardEntity idCardEntity = data.getIdCard();

                        if (idCardEntity != null) {
                            values.put(GhContentProvider.KEY_IS_CERTIFICATED, !TextUtils.isEmpty(data.getIdCard().getId())); // 是否认证
                            values.put(GhContentProvider.KEY_IS_ADULT,
                                    data.getIdCard().getMinor() == null
                                            || !data.getIdCard().getMinor()
                            );
                        } else {
                            values.put(GhContentProvider.KEY_IS_CERTIFICATED, false);
                            values.put(GhContentProvider.KEY_IS_ADULT, false);
                        }

                        EventBus.getDefault().post(new EBReuse(Constants.EB_REALNAME_RESULT));

//                     new GhContentProvider().localInsert( HaloApp.getInstance().getApplication(),values);
                        try {
                            // Unknown URL content://com.gh.gamecenter.provider/certification
                            // TODO 将 com.gh.gamecenter 改成 BuildConfig.ApplicationID
                            HaloApp.getInstance().getContentResolver().insert(Uri.parse("content://com.gh.gamecenter.provider/certification"), values);
                        } catch (Exception exception) {
                            SentryHelper.INSTANCE.onEvent("CERTIFICATION_INSERT_ERROR", "exception_digest", exception.getLocalizedMessage());
                            exception.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 下次应用启动再上报
     *
     * @param context
     * @param throwable
     */
    public static void reportException(Context context, Throwable throwable) {

        CommonDebug.logMethodWithParams(context, "ERRMSG", throwable);

        // 上传错误数据
        try {
            DataCollectionUtils.uploadError(context, Log.getStackTraceString(throwable));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
