package com.ydl.component.base;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Process;
import android.webkit.WebView;

import androidx.multidex.MultiDex;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.meituan.android.walle.WalleChannelReader;
import com.tencent.qcloud.tuicore.calling.trtccalling.model.TRTCCalling;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.ydl.audioim.api.IAudioImService;
import com.ydl.component.route.PlatformTempCommonRouteImpl;
import com.ydl.confide.BuildConfig;
import com.ydl.media.audio.AudioPlayer;
import com.ydl.media.audio.manager.MediaSessionManager;
import com.ydl.media.audio.manager.NotifyManager;
import com.ydl.ydl_image.manager.YDLImageCacheManager;
import com.ydl.ydlcommon.base.BaseApp;
import com.ydl.ydlcommon.modular.ModularServiceManagerKt;
import com.ydl.ydlcommon.router.YdlCommonRouterManager;
import com.ydl.ydlcommon.utils.AppProgressUtils;
import com.ydl.ydlcommon.utils.Utils;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.consultant.preview.TestImageLoader;
import com.yidianling.consultant.preview.ZoomMediaLoader;
import com.yidianling.course.lifeCallback.CoursePlayLifecycle;


/**
 * @Author:      刘鹏
 * @Description:  配置一些初始化数据，方便在组件中测试功能
 * @CreateDate:  3/10/21 1:35 PM
 * -------------------------------
 * @UpdateUser:
 * @UpdateDate:  3/10/21 1:35 PM
 * @UpdateRemark:
 * @Version:
 */
public class ComponentTestApp extends BaseApp {

    private static ComponentTestApp mComponentTestAppContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mComponentTestAppContext = this;
        AudioPlayer.Companion.get().init(this);
        NotifyManager.Companion.get().init(this);
        MediaSessionManager.Companion.get().init(this);
        LogUtil.debug = BuildConfig.DEBUG;
        com.ydl.ydlcommon.utils.LogUtil.debug = BuildConfig.DEBUG;

        webviewSetPath(this);
        ZoomMediaLoader.getInstance().init(new TestImageLoader());

        if (!BuildConfig.DEBUG && Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {//release包去除，debug包不去除，用于检测是否还有反射api的方法
            //去掉在Android P上的提醒弹窗 Detected problems with API
            Utils.closeAndroidPDialog();
        }
        //模块注册
        moduleRegister();
        //判断是否为主进程
        //初始化umeng
        initUmeng();

        registerActivityLifecycleCallbacks(new CoursePlayLifecycle());

        ModularServiceManagerKt.findRouteService(IAudioImService.class).initAgoraRtc(this);

        Fresco.initialize(this);

        TRTCCalling.sharedInstance(this).setMdtCallBack(new TRTCCalling.MdtCallBack() {
            @Override
            public void onReceiveNewInvitation(String roomId) {
                ToastUtil.toastShort("电话邀请" + roomId);
            }

            @Override
            public void onInviteeAccepted(String roomId) {
                ToastUtil.toastShort("接受邀请"+roomId);
            }

            @Override
            public void onInviteeRejected(String roomId) {
                ToastUtil.toastShort("拒绝邀请"+roomId);
            }
        });
    }

    private void initUmeng() {
        String channel = WalleChannelReader.getChannel(this);
        if (channel == null || channel == "null") {
            channel = "test";
        }

        //umeng
        String umAppkey = "56970affe0f55a9cda001e24";
        channel = "android_" + channel;
        initUM(umAppkey, channel);
        PlatformConfig.setWeixin("wx57a9d930270498c7", "17c031f02500ded3457a80e69d8e5e45");
        PlatformConfig.setWXFileProvider("com.cxzapp.yidianling.fileprovider");
        PlatformConfig.setQQZone("1105070461", "6BvkUnk6wXJekcgR");
        PlatformConfig.setQQFileProvider("com.cxzapp.yidianling.fileprovider");

        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        MobclickAgent.setCatchUncaughtExceptions(!BuildConfig.DEBUG);

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

    public static ComponentTestApp getAppContext() {
        return mComponentTestAppContext;
    }

    private void moduleRegister() {
        YdlCommonRouterManager.INSTANCE.initYdlCommonRoute(new PlatformTempCommonRouteImpl());//
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (AppProgressUtils.isMainProcess(this)) {
            YDLImageCacheManager.onTrimMemory(this, level);
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (AppProgressUtils.isMainProcess(this)) {
            YDLImageCacheManager.onLowMemory(this);
        }
    }


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


    public void webviewSetPath(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(context);
            if (!"com.cxzapp.yidianling".equals(processName)) {//判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }


    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }
}
