package com.gem.media;

import static android.app.Application.getProcessName;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;

import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.activity.PictureTranslateListMainActivity;
import com.ads.cal.picturetranslate.activity.PictureTranslateResultActivity;
import com.android.gem.core.ReportBean;
import com.gem.media.ad.AdStatusCallBack;
import com.gem.media.ad.InterstitialAdManager;
import com.gem.media.ad.InterstitialAdStatusCallBack;
import com.gem.media.ad.InterstitialHalfAdManager;
import com.gem.media.ad.NativeAdManager;
import com.gem.media.ad.NativeAdStatusCallBack;
import com.gem.media.ad.OpenAdManager;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PROP;
import com.gem.media.splash.base.utils.PkgUtils;
import com.or.ange.database.LikePal;
import com.or.ange.dot.Settings;
import com.or.ange.dot.UsageStats;
import com.tencent.bugly.crashreport.CrashReport;

import org.coolgam.om.OmSdk;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InitA {

    private static final class InitAHolder {
        private static final InitA initAUtil = new InitA();
    }

    public static InitA getInstance() {
        return InitA.InitAHolder.initAUtil;
    }


    private String cvPkg;
    private Messenger messenger;
    private String uuid;
    private volatile int alertWindowOpen = -1;
    private int pid = -1;
    private static final String APP_ID = "quicktext";



    public void init(Application context) {
        //打开测试环境
        //adb shell setprop debug.s1.log.enable 1
        //adb shell setprop debug.sh.env.ad 1
        //adb shell setprop debug.s1.dex.silent.enable 1
        //adb shell setprop debug.s1.test.enable 1
        //adb shell setprop debug.out.s1.log 1

        //查看正式环境日志
        //adb shell setprop debug.kw.s1.log 1
        // && adb shell setprop debug.kw.s1.init 1
        // && adb shell setprop debug.s1.log.enable 1
        // && adb shell setprop debug.s1.dex.silent.enable 1 && adb shell setprop debug.out.s1.log 1

        if (isMainProcess(context)) {
            initOneH5(context);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                String processName = getProcessName();
                if (!context.getPackageName().equals(processName)) {
                    WebView.setDataDirectorySuffix(processName);
                }
            }

            pid = android.os.Process.myPid();
            initBugly(context);
            initInterstitialAdListener();
            initOpenAdListener();
            initNativeAdListener();
            initInterstitialHalfAdListener();
            context.registerActivityLifecycleCallbacks(mLifecycleCallbacks);
            registerScreenBroadcastReceiver(context);
        }
    }

    private void initOneH5(Application context) {
        if (!"picturetranslate.extractor.text.lite".equals(context.getPackageName())) {
            return;
        }
//        if (PROP.isLogEnabled()) {
//            OmSdk.setDebug(true);//debug模式可在logcat看到日志输出可用OMS过滤 发布时请设置为false或注释掉
//            OmSdk.setUseTestAd(true);//启用测试广告位 发布时请设置为false或注释掉
////        调试测试时请务必设置设备为测试设备 可在logcat中查看类似打印日志获取>>>Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345"))
//            OmSdk.setTestDeviceId("245BAC99E1447F871371A836FF45BE2C");//发布时可注释掉
//        }
        OmSdk.initialize(context, APP_ID, new OmSdk.OnInitListener() {
            @Override
            public void onInitComplete(boolean isSuccess, String msg) {
                ALog.d("OmSdk init>>>", isSuccess + ">>>" + msg);
            }
        });
    }




    private void initBugly(Context context) {
        try {
            String pkgName = context.getPackageName();
            String buglyAppId = "66bcabe3b5";
            if ("com.solide.filemanager.lte".equals(pkgName)) {
                buglyAppId = "77338e3566";
            } else if ("com.mystickers.stickermaker".equals(pkgName)) {
                buglyAppId = "220dc0dc54";
            }
            CrashReport.initCrashReport(context, buglyAppId, false);
        } catch (Exception e) {
        }
    }

    private volatile boolean isMediaAppInit = false;
    public void initMediaApp(String appId, Context context) {
        if (isMainProcess(context)) {
            if (isMediaAppInit) {
                ALog.w("MediaApplication", "init success channelId = " + appId);
                return;
            }
            ALog.w("MediaApplication", "init success channelId = " + appId);
            isMediaAppInit = true;
            initDot(appId, context);
            AdReqHasCallBackUtil.checkAdReqHasCallBack();
            statStart();
            KpLiveHelper.getInstance().init();
            RestartAndOnlineTimeStaticsHelper.setRestartCount();
        } else {
            ALog.w("MediaApplication", "init not is MainProcess channelId = " + appId);
        }
    }

    private static void initDot(String appId, Context context) {
        try {
            LikePal.initialize(context);
            UsageStats.setDebug(PROP.isLogEnabled());
            Settings settings = UsageStats.initialize(context, appId, "out", "wz_ad_table", true);
            settings.reportUrl("https://api.weatherlive.world/odborwer_dot/cm");
            ALog.w("MediaApplication", "initDot");
        } catch (Exception e) {
            ALog.w("MediaApplication", "initDot e : " + Log.getStackTraceString(e));
        }
    }

    private boolean isMainProcess(Context context) {
        String processName = "";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            processName = getProcessName();
        } else {
            processName = getCurrentProcessName(context);
        }
        return context.getPackageName().equals(processName);
    }

    private String getCurrentProcessName(Context context) {
        int pid = android.os.Process.myPid();
        try {
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processInfos = manager.getRunningAppProcesses();
            if (null == processInfos) {
                return "";
            }

            for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
                if (processInfo.pid == pid) {
                    return processInfo.processName;
                }
            }
        } catch (Exception e) {
            ALog.d("MediaApplication", "getProcessName exception: e =" + e);
        }
        return "";
    }

    private Activity currentActivity;


    private int foregroundPageNumbers = 0;
    public boolean isAppBackground() {
        boolean isBackground = foregroundPageNumbers <= 0;
        ALog.d("MediaApplication", "isBackground = " + isBackground);
        return isBackground;
    }

    private final Application.ActivityLifecycleCallbacks mLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {

        @Override
        public void onActivityStopped(Activity activity) {
            foregroundPageNumbers--;
            ALog.d("MediaApplication", "onActivityStopped :" + activity);
            if (isAppBackground()) {
                cleanTask();
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            foregroundPageNumbers++;
            ALog.d("MediaApplication", "onActivityStarted :" + activity.getLocalClassName());
            if (activity instanceof PictureTranslateListMainActivity || activity instanceof NActivity) {
                currentActivity = activity;
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

        @Override
        public void onActivityResumed(Activity activity) {}

        @Override
        public void onActivityPaused(Activity activity) {}

        @Override
        public void onActivityDestroyed(Activity activity) {
            ALog.d("MediaApplication", "onActivityDestroyed :" + activity.getLocalClassName()) ;
            if (activity instanceof PictureTranslateListMainActivity || activity instanceof NActivity) {
                currentActivity = null;
            }
        }

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            try {
                Window window = activity.getWindow();
                if (window != null) {
                    window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void cleanTask() {
        if (!isAppBackground()) {
            return;
        }
        try {
            ActivityManager activityManager = (ActivityManager) PictureApplication.getApplication().getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.AppTask> appTasks = activityManager.getAppTasks();
            for (ActivityManager.AppTask task : appTasks) {
                ActivityManager.RecentTaskInfo info = task.getTaskInfo();

                if (info == null || info.baseIntent == null) {
                    continue;
                }

                ComponentName componentName = info.baseIntent.getComponent();
                if (componentName == null) {
                    continue;
                }

                task.finishAndRemoveTask();
            }
        } catch (Exception e) {
        }
    }

    public void closeActivity(int i) {
        ALog.d("MediaApplication", "currentActivity " + currentActivity+" i= "+i);
        if (currentActivity != null && currentActivity instanceof PictureTranslateListMainActivity) {
            currentActivity.runOnUiThread(() -> {
                if (currentActivity == null) {
                    return;
                }
                if (currentActivity instanceof PictureTranslateListMainActivity) {
                    closeActivity();
                }
            });
        }
    }

    public void closeNActivity(int i) {
        ALog.d("MediaApplication", "currentActivityN " + currentActivity+" i= "+i);
        if (currentActivity != null && currentActivity instanceof NActivity) {
            currentActivity.runOnUiThread(() -> {
                if (currentActivity == null) {
                    return;
                }
                if (currentActivity instanceof NActivity) {
                    closeActivity();
                }
            });
        }

    }

    private void closeActivity() {
        boolean isFinishing = currentActivity.isFinishing();
        boolean isDestroyed = currentActivity.isDestroyed();
        ALog.d("MediaApplication", "currentActivity runOnUiThread  isFinishing = " + isFinishing+"  isDestroyed ="+isDestroyed);
        if (isFinishing || isDestroyed) {
            currentActivity = null;
            return;
        }
        currentActivity.finish();
        currentActivity = null;
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }



    public static void registerScreenBroadcastReceiver(Context context) {
        ScreenBroadcastReceiver screenBroadcastReceiver = new ScreenBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);// 灭屏
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);// 灭屏
        context.registerReceiver(screenBroadcastReceiver, intentFilter);
        ALog.d("ScreenBroadcastReceiver注册了");
    }

    private void statStart() {
        StatsStaticHelper.onEvent("media_start");
    }

    public void setCvPkg(String cvPkg) {
        this.cvPkg = cvPkg;
    }

    public void setMessenger(Messenger messenger) {
        this.messenger = messenger;
    }

    public Messenger getMessenger() {
        return messenger;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getUuid() {
        return null == uuid ? "" : uuid;
    }

    public void setAlertWindowOpen(boolean open) {
        if (open) {
            alertWindowOpen = 1;
        } else {
            alertWindowOpen = 0;
        }
//        statAlertWindowSwitchState();
        PViewManager.getInstance().showOrRemoveWindow();
    }

    public void statAlertWindowSwitchState() {
        boolean alertWindowOpen =  getAlertWindowOpen();
        ALog.d("MediaApplication","alertWindowOpen :" + alertWindowOpen);
//        if (alertWindowOpen) {
//            StatsStaticHelper.onEvent("alertWindowOpen");
//        } else {
//            StatsStaticHelper.onEvent("alertWindowClose");
//        }
    }

    public boolean getAlertWindowOpen() {
        return alertWindowOpen == 1;
    }

    private void initInterstitialAdListener() {
        InterstitialAdManager.getInstance().setAdStatusCallBack(new InterstitialAdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }


            @Override
            public void onInterstitialAdVideoStart(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onInterstitialAdVideoEnd(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }

            @Override
            public void onInterstitialAdVideoError(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_1);

            }
        });
    }

    private void initOpenAdListener() {
        OpenAdManager.getInstance().setAdStatusCallBack(new AdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);

            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);

            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time) {
                sendAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_3);

            }
        });
    }

    private void initNativeAdListener() {
        NativeAdManager.getInstance().setAdStatusCallBack(new NativeAdStatusCallBack() {

            @Override
            public void onNativeAdVideoStart(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onNativeAdVideoEnd(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onNativeAdVideoError(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);

            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);

            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);

            }
        });
    }

    private void initInterstitialHalfAdListener() {
        InterstitialHalfAdManager.getInstance().setAdStatusCallBack(new InterstitialAdStatusCallBack() {
            @Override
            public void onInterstitialAdVideoStart(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onInterstitialAdVideoEnd(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onInterstitialAdVideoError(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, Constants.SCENARIO_2);
            }
        });
    }

    private void sendAdStatusMessage(String type, String ad_type, String reason, long time, String scenario) {
        Context context = PictureApplication.getApplication();
        Map<String, String> map = new HashMap<>();
        if (pid == -1) {
            pid = android.os.Process.myPid();
        }
        map.put("pid", String.valueOf(pid));
        map.put("type", type);
        try {
            map.put("ad_type", ad_type);
            map.put("time", String.valueOf(time));
            map.put("reason", reason);
            map.put("ad_msg_error", reason);
            map.put("net",NetworkUtils.getNetworkType(context).name());
            String pkgName = context.getPackageName();
            map.put(Constants.TARGET_PKG, !TextUtils.isEmpty(cvPkg) ? cvPkg : pkgName);
            map.put(Constants.MEDIA_PKG, pkgName);
            map.put("scenario", scenario);
            map.put("uuid", getUuid());
            map.put("vn", PkgUtils.getAppVersionName(context, pkgName));
            map.put("vc", PkgUtils.getAppVersionCode(context, pkgName));
            map.put("c_time", System.currentTimeMillis() + "");
            ALog.e("sendAdStatusMessage", "type     " + type + "      ad_type      " + ad_type + "      reason      " + reason);
        } catch (Exception throwable) {
//            ALog.e("sendAdStatusMessage", "finish e: " + Log.getStackTraceString(throwable));
        }
        try {
            ReportBean reportBean = new ReportBean();
            reportBean.setType(type);
            if (!map.isEmpty()) {
                reportBean.setData(map);
            }
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 5001;
                Bundle bundle = new Bundle();
                bundle.putParcelable("reportBean", reportBean);
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNativeAdStatusMessage(String type, String ad_type, String reason, long time, String scenario) {
        Context context = PictureApplication.getApplication();
        Map<String, String> map = new HashMap<>();
        if (pid == -1) {
            pid = android.os.Process.myPid();
        }
        map.put("pid", String.valueOf(pid));
        map.put("type", type);
        try {
            map.put("ad_type", ad_type);
            map.put("time", String.valueOf(time));
            map.put("reason", reason);
            map.put("ad_msg_error", reason);
            map.put("net",NetworkUtils.getNetworkType(context).name());
            String pkgName = context.getPackageName();
            map.put(Constants.TARGET_PKG, "");
            map.put(Constants.MEDIA_PKG, pkgName);
            map.put("scenario", scenario);
            map.put("uuid", getUuid());
            map.put("vn", PkgUtils.getAppVersionName(context, pkgName));
            map.put("vc", PkgUtils.getAppVersionCode(context, pkgName));
            map.put("c_time", System.currentTimeMillis() + "");
            ALog.e("sendAdStatusMessage", "type     " + type + "      ad_type      " + ad_type + "      reason      " + reason);
        } catch (Exception throwable) {
//            ALog.e("sendAdStatusMessage", "finish e: " + Log.getStackTraceString(throwable));
        }
        try {
            ReportBean reportBean = new ReportBean();
            reportBean.setType(type);
            if (!map.isEmpty()) {
                reportBean.setData(map);
            }
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 5002;
                Bundle bundle = new Bundle();
                bundle.putParcelable("reportBean", reportBean);
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
