package com.ydl.component.base;


import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Process;
import android.support.annotation.RequiresApi;

import com.facebook.stetho.Stetho;
import com.meituan.android.walle.WalleChannelReader;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.ydl.component.BuildConfig;
import com.ydl.component.MainActivity;
import com.ydl.media.audio.PlayService;
import com.ydl.ydlcommon.base.config.YDLConstants;
import com.ydl.ydlcommon.base.delegate.IAppLifecycles;
import com.ydl.ydlcommon.utils.YdlBuryPointUtil;
import com.yidianling.course.lifeCallback.CoursePlayLifecycle;
import com.yidianling.im.config.NimApplication;

import org.jetbrains.annotations.NotNull;

import io.flutter.view.FlutterMain;

/**
 * Created by haorui on 2019-09-02.
 * Des:
 */
public class DemoAppLifecycles implements IAppLifecycles {

    @Override
    public void attachBaseContext(@NotNull Context base) {

    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onCreate(@NotNull Application application) {
        //模块初始化
        moduleInit(application);
        if (NIMUtil.isMainProcess(application)) {
            //第三方SDK初始化
            initThirdServiceSDK(application);
            //Flutter 初始化需要在主线程中执行
            FlutterMain.startInitialization(application);

            //        FlutterMain.ensureInitializationComplete(application, null);
            //
            //        FlutterEngine flutterEngine = new FlutterEngine(application);
            //        flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
            //        YDLCommonPlugin plugin = new YDLCommonPlugin();
            //        flutterEngine.getLocalizationChannel().channel.setMethodCallHandler(plugin);

            Intent intent = new Intent(application, PlayService.class);
            application.startService(intent);
            application.registerActivityLifecycleCallbacks(new CoursePlayLifecycle());

            Stetho.initializeWithDefaults(application);
        }
    }

    @Override
    public void onTerminate(@NotNull Application application) {
    }

    private void moduleInit(Application application) {
        NimApplication.getInstance().initIm(application, MainActivity.class);
    }

    private void initThirdServiceSDK(Application application) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                //设置线程优先级，不与主线程抢资源
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

                //子线程中初始化X5内核，防止ANR问题
                initX5();

                //数据埋点初始化--一定要放在主进程中
                YdlBuryPointUtil.init(application);
                if (DemoGlobalConfig.appEnv.equals(YDLConstants.ENV_PROD)){
//                    YDLavManager.Companion.getInstances().init(application, "3387e9b251f3491e9221a9877e8f7830");
                }else {
//                    YDLavManager.Companion.getInstances().init(application, "13b1536698f64905a1e7e5bb978ba821");
                }

                //bugly
                String packageName = application.getPackageName();
                String channel = WalleChannelReader.getChannel(application);
                if (channel == null || channel.equals("null")) {
                    channel = "test";
                }
                CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(application);
                strategy.setAppChannel(channel);
                String appkey = BuildConfig.DEBUG ? "630a3a5cea" : "3939e71afa";
                CrashReport.initCrashReport(application, appkey, BuildConfig.DEBUG, strategy);

                //umeng
                String umAppkey = null;
                if (packageName.endsWith("yidianling")) {
                    umAppkey = "56970affe0f55a9cda001e24";
                    channel = "android_" + channel;
                    initUM(umAppkey, channel,application);
                    PlatformConfig.setWeixin("wx57a9d930270498c7", "17c031f02500ded3457a80e69d8e5e45");
                }
                PlatformConfig.setQQZone("1105070461", "6BvkUnk6wXJekcgR");
                MobclickAgent.setScenarioType(application, MobclickAgent.EScenarioType.E_DUM_NORMAL);
                MobclickAgent.setCatchUncaughtExceptions(!BuildConfig.DEBUG);

                //开启友盟集成测试
                UMConfigure.setLogEnabled(BuildConfig.DEBUG);

                //安全检测
                //YDLAppProtector.init();

            }
        }.start();
    }



    private void initUM(String umAppKey, String channel, Application application) {
        /**
         * 初始化common库
         * 参数1:上下文，不能为空
         * 参数2:友盟 app key
         * 参数3:友盟 channel
         * 参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         * 参数5:Push推送业务的secret
         */
        UMConfigure.init(application, umAppKey, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
        UMShareAPI.init(application, umAppKey);
    }


    /**
     * 初始化X5内核
     */
    private void initX5() {
//        if (!QbSdk.isTbsCoreInited()) {//// preinit只需要调用一次，如果已经完成了初始化，那么就直接构造view
//            QbSdk.preInit(application, null);// 设置X5初始化完成的回调接口
//        }
//
//        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
//
//            @Override
//            public void onViewInitFinished(boolean arg0) {
//                //初始化完成回调
//            }
//
//            @Override
//            public void onCoreInitFinished() {
//            }
//        };
//        QbSdk.initX5Environment(application, cb);
    }


}