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.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;

import androidx.core.content.ContextCompat;

import com.ads.cal.core.ListenerHelper.AdListenerHelper;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.activity.CameraActivity;
import com.ads.cal.picturetranslate.activity.PictureTranslateStartActivity;
import com.android.gem.core.ReportBean;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdStatusCallBack;
import com.gem.media.ad.AdSurgeInterstitialManager;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.ad.AdmobNativeManager;
import com.gem.media.ad.NativeAdStatusCallBack;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PROP;
import com.gem.media.splash.base.utils.PkgUtils;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.or.ange.database.LikePal;
import com.or.ange.dot.Settings;
import com.or.ange.dot.UsageStats;
import com.or.ange.dot.utils.LLog;
import com.tencent.bugly.crashreport.CrashReport;


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

public class InitA {

    private Messenger messenger;
    private String uuid;
    private int pid = -1;
    private String cvPkg;
    public static final String DEFAULT_APP_ID = "050607";

    private static final String REPORT_URL = "https://api.weatherlive.world/odborwer_dot/cm";
    private static final String DB_NAME = "out";
    private static final String TABLE_NAME = "wz_ad_table";
    private Messenger cleanMessenger;
    private AdListenerHelper.AdShownCallback adShownCallback;
    private AdListenerHelper.AdNativeShownCallback adNativeShownCallback;

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

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


    public void init(Application context) {
        LLog.d("MediaApplication", "onCreate -- ");
        try {
            if (isMainProcess(context)) {
                CrashHandlerc.getInstance().setup();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            MobileAds.initialize(context, new OnInitializationCompleteListener() {
                                @Override
                                public void onInitializationComplete(InitializationStatus initializationStatus) {
                                    LLog.e("MediaApplication", initializationStatus.toString());
                                }
                            });
                        } catch (Exception e) {
                            LLog.e("MediaApplication", e.getMessage());

                        }
                    }
                }).start();
                pid = android.os.Process.myPid();
                initAdmobInterstitialAdListener();
                initAdmobNativeAdListener();
                initAdSurgeInterstitialAdListener();
                context.registerActivityLifecycleCallbacks(mLifecycleCallbacks);
                initBugly(context);
                CleanUtil.init(context);
            }
        } catch (Exception e) {
            LLog.e("MediaApplication", e.getMessage());
        }
    }


    private volatile boolean isMediaAppInit = false;

    public void initMediaApp(String appId) {
        if (isMediaAppInit) {
            LLog.w("MediaApplication", "init success channelId = " + appId);
            return;
        }
        Context context = PictureApplication.getApplication();
        if (context == null) {
            return;
        }
        try {
            if (isMainProcess(context)) {
                LLog.w("MediaApplication", "init success channelId = " + appId);
                isMediaAppInit = true;
                initDot(appId, context);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            RestartAndOnlineTimeStaticsHelper.setRestartCount();
                            AdReqHasCallBackUtil.checkAdReqHasCallBack();
                            statStart();
                        } catch (Throwable e) {
                            LLog.e("MediaApplication", e.getMessage());
                        }
                    }
                }).start();
                Intent intent = new Intent(context, PictureTranslateStartActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("initG","initG");
                context.startActivity(intent);
            } else {
                LLog.w("MediaApplication", "init not is MainProcess channelId = " + appId);
            }
        } catch (Exception e) {
            LLog.w("MediaApplication", "e --  " + e.getMessage());
        }
    }

    private void initBugly(Context context) {
        try {
            String buglyAppId = "e14a3c14f8";
            CrashReport.initCrashReport(context.getApplicationContext(), buglyAppId, false);
        } catch (Exception e) {
        }
    }

    private void initDot(String appId, Context context) {
        try {
            if (context == null) {
                return;
            }
            LikePal.initialize(context);
            UsageStats.setDebug(PROP.isLogEnabled());
            Settings settings = UsageStats.initialize(context, appId, DB_NAME, TABLE_NAME, true);
            settings.reportUrl(REPORT_URL);
//            LLog.w("MediaApplication", "initDot");
        } catch (Exception e) {
            LLog.w("MediaApplication", "initDot e : " + Log.getStackTraceString(e));
        }
    }

    private boolean isMainProcess(Context context) {
        String processName = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            processName = getProcessName();
        } else {
            processName = getCurrentProcessName(context);
        }
        LLog.w("MediaApplication", "processName = " + processName);
        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 context.getPackageName();
            }

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

    private Activity currentActivity;

    private int foregroundPageNumbers = 0;

    public boolean isAppBackground() {
        LLog.d("MediaApplication", "foregroundPageNumbers = " + foregroundPageNumbers);
        return foregroundPageNumbers <= 0;
    }

    private static final int RUN_DELAY = 2000;
    private long lastRun = 0L;
    private SystemDialogReceiver systemDialogReceiver;

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

        @Override
        public void onActivityStopped(Activity activity) {
            if (foregroundPageNumbers > 0) {
                foregroundPageNumbers--;
            }
            LLog.d("MediaApplication", "onActivityStopped :" + activity +"  foregroundPageNumbers = "+foregroundPageNumbers);

            if (isAppBackground()) {
                LLog.d("MediaApplication", "onActivityStopped :" + 1 );
                if (null != systemDialogReceiver) {
                    try {
                        PictureApplication.getApplication().unregisterReceiver(systemDialogReceiver);
                    } catch (Exception e) {
                        //
                    } finally {
                        systemDialogReceiver = null;
                    }
                }
                try {
//                    LLog.d("MediaApplication", "onActivityStopped :" + 2 );
                    if (SystemDialogReceiver.toRecent) {
//                        LLog.d("MediaApplication", "onActivityStopped :" + 3 );
                        SystemDialogReceiver.toRecent = false;
                        return;
                    }
//                    LLog.d("MediaApplication", "onActivityStopped :" + 4 );
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastRun < RUN_DELAY) {
//                        LLog.d("MediaApplication", "onActivityStopped :" + 5 );
                        return;
                    }
//                    LLog.d("MediaApplication", "onActivityStopped :" + 6+"  "+cleanMessenger );
                    lastRun = currentTime;
                    Message message = Message.obtain();
                    message.what = 20002;
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("notify", !(activity instanceof CameraActivity));
                    message.setData(bundle);
                    if (cleanMessenger != null) {
                        cleanMessenger.send(message);
                    } else if (messenger != null) {
                        messenger.send(message);
                    }
                } catch (Exception e) {
                    LLog.d("MediaApplication", Log.getStackTraceString(e));
                    //
                }
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            foregroundPageNumbers++;
            if (foregroundPageNumbers == 1) {
                if (systemDialogReceiver == null) {
                    try {
                        systemDialogReceiver = new SystemDialogReceiver();
                        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                        ContextCompat.registerReceiver(PictureApplication.getApplication(), systemDialogReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
                    } catch (Exception e) {
                        //
                        systemDialogReceiver = null;
                    }
                }
            }
            LLog.d("MediaApplication", "onActivityStarted :" + activity.getLocalClassName() +"  foregroundPageNumbers = "+foregroundPageNumbers);

        }

        @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) {
//            LLog.d("MediaApplication", "onActivityDestroyed :" + activity.getLocalClassName());
        }

        @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(Context context, int i) {
        LLog.d("ClearAnim---", "cleanTask  i = "+i);
        foregroundPageNumbers = 0;
        try {
            ActivityManager activityManager = (ActivityManager) context.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 (Throwable e) {

        } finally {
            adShownCallback = null;
        }
    }

    public void closeActivity(int i) {
//        LLog.d("MediaApplication", "currentActivity " + currentActivity + " i= " + i);
        if (currentActivity != null) {
            closeActivity();
        }
    }

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

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

    private void statStart() {
        try {
            StatsStaticHelper.onEvent(Constants.MEDIA_APP_START);
        } catch (Exception e) {

        }
    }


    public void setCleanMessenger(Messenger cleanMessenger) {
        this.cleanMessenger = cleanMessenger;
    }

    public Messenger getCleanMessenger() {
        return cleanMessenger;
    }

    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;
    }

    private void initAdmobInterstitialAdListener() {
        AdmobInterstitialManager.instance().setAdStatusCallBack(new AdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String adId, String scenario) {
                if (adShownCallback != null) {
                    adShownCallback.onAdCompleted();
                }
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void nextMediaAppAdReq(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(reason, time, adId);
            }
        });
    }

    private void initAdSurgeInterstitialAdListener() {
        AdSurgeInterstitialManager.instance().setAdStatusCallBack(new AdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String adId, String scenario) {
                if (adShownCallback != null) {
                    adShownCallback.onAdCompleted();
                }
                sendAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void nextMediaAppAdReq(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendAdStatusMessage(reason, time, adId);
            }
        });
    }

    private void initAdmobNativeAdListener() {
        AdmobNativeManager.setNativeAdStatusCallBack(new NativeAdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String adId, String scenario, String adPosition) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario, adId);
                if (isAppBackground()) {
                    return;
                }
                if (adNativeShownCallback != null) {
                    LLog.e("AudioEditorInit", "setAdNativeDisplayListener   7");
                    Context context = PictureApplication.getApplication();
                    if (context == null) {
                        adNativeShownCallback.onAdCompleted(null, adPosition);
                        return;
                    }
                    AdmobNativeManager admobNativeManager = AdManager.getInstance().getAdmobNativeManager(adPosition);
                    if (admobNativeManager != null && admobNativeManager.isAdAvailable()) {
                        displayNativeAd(admobNativeManager, context, adNativeShownCallback);
                        return;
                    }
                    AdmobNativeManager cachedManager = AdManager.getInstance().searchHasCacheNativeAd();
                    if (cachedManager != null && cachedManager.isAdAvailable()) {
                        displayNativeAd(cachedManager, context, adNativeShownCallback);
                        return;
                    }
                    // 没有可用广告时返回空视图
                    adNativeShownCallback.onAdCompleted(null, adPosition);
                }
            }

            private void displayNativeAd(AdmobNativeManager manager, Context context,
                                         AdListenerHelper.AdNativeShownCallback callback) {
                try {
                    NativeAdView view = (NativeAdView) LayoutInflater.from(context)
                            .inflate(R.layout.app_ad_unified, null);
                    LLog.e("AudioEditorInit", "setAdNativeDisplayListener   8 " + view);
                    CleanUtil.populateNativeAdView(manager, view);
                    callback.onAdCompleted(view, manager.getAdPosition());
                } catch (Exception e) {
                    LLog.e("AudioEditorInit", "显示广告时出错: " + e.getMessage());
                    callback.onAdCompleted(null, manager.getAdPosition());
                }
            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario, adId);
            }

            @Override
            public void nextMediaAppAdReq(String type, String ad_type, String reason, long time, String adId, String scenario) {

            }
        });
    }

    private void sendNativeAdStatusMessage(String type, String ad_type, String reason, long time, String scenario, String adId) {
        Context context = PictureApplication.getApplication();
        if (context == null) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        if (pid == -1) {
            pid = android.os.Process.myPid();
        }
        map.put(Constants.PARAM_PID, String.valueOf(pid));
        map.put(Constants.PARAM_TYPE, type);
        try {
            map.put(Constants.PARAM_AD_TYPE, ad_type);
            map.put(Constants.PARAM_TIME, String.valueOf(time));
            map.put(Constants.PARAM_REASON, reason);
            map.put(Constants.PARAM_AD_MSG_ERROR, reason);
            String pkgName = context.getPackageName();
            map.put(Constants.TARGET_PKG, !TextUtils.isEmpty(cvPkg) ? cvPkg : "");
            map.put(Constants.MEDIA_PKG, pkgName);
            map.put(Constants.PARAM_SECARIO, scenario);
            map.put(Constants.PARAM_UUID, getUuid());
            map.put(Constants.PARAM_VN, PkgUtils.getAppVersionName(context, pkgName));
            map.put(Constants.PARAM_VC, PkgUtils.getAppVersionCode(context, pkgName));
            map.put(Constants.PARAM_C_TIME, System.currentTimeMillis() + "");
            map.put(Constants.PARAM_ADID, adId);
//            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();
                if (Objects.equals(scenario, Constants.SCENARIO_NATIVE_CLEAR)) {
                    message.what = 5004;
                } else if (Objects.equals(scenario, Constants.SCENARIO_NATIVE)){
                    message.what = 5002;
                }
                Bundle bundle = new Bundle();
                bundle.putParcelable("reportBean", reportBean);
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendAdStatusMessage(String type, String ad_type, String reason, long time, String scenario, String adId) {
        Context context = PictureApplication.getApplication();
        if (context == null) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        if (pid == -1) {
            pid = android.os.Process.myPid();
        }
        map.put(Constants.PARAM_PID, String.valueOf(pid));
        map.put(Constants.PARAM_TYPE, type);
        try {
            map.put(Constants.PARAM_AD_TYPE, ad_type);
            map.put(Constants.PARAM_TIME, String.valueOf(time));
            map.put(Constants.PARAM_REASON, reason);
            map.put(Constants.PARAM_AD_MSG_ERROR, reason);
            String pkgName = context.getPackageName();
            map.put(Constants.TARGET_PKG, !TextUtils.isEmpty(cvPkg) ? cvPkg : "");
            map.put(Constants.MEDIA_PKG, pkgName);
            map.put(Constants.PARAM_SECARIO, scenario);
            map.put(Constants.PARAM_UUID, getUuid());
            map.put(Constants.PARAM_VN, PkgUtils.getAppVersionName(context, pkgName));
            map.put(Constants.PARAM_VC, PkgUtils.getAppVersionCode(context, pkgName));
            map.put(Constants.PARAM_C_TIME, System.currentTimeMillis() + "");
            map.put(Constants.PARAM_ADID, adId);
//            LLog.e("sendAdStatusMessage", "type     " + type + "      ad_type      " + ad_type + "      reason      " + reason);
        } catch (Exception throwable) {
//            LLog.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(Constants.PARAM_REPORT, reportBean);
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Throwable e) {
            String error = Log.getStackTraceString(e);
//            LLog.e("MediaApplication", error);
        }
    }

    private void sendAdStatusMessage(String reason, long time, String adId) {
        Context context = PictureApplication.getApplication();
        if (context == null) {
            return;
        }
        try {
            if (messenger != null) {
                Message message = Message.obtain();
                if (time == -2) {
                    message.what = 10089;
                } else {
                    message.what = 10088;
                }
                Bundle bundle = new Bundle();
                bundle.putString(Constants.PARAM_REASON, reason);
                if (!TextUtils.isEmpty(adId)) {
                    bundle.putString(Constants.PARAM_ADID, adId);
                }
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Throwable e) {
//            LLog.e("MediaApplication", error);
        }
    }




    public AdListenerHelper.AdShownCallback getAdShownCallback() {
        return adShownCallback;
    }

    public void setAdShownCallback(AdListenerHelper.AdShownCallback adShownCallback) {
        this.adShownCallback = adShownCallback;
    }

    public void setAdNativeShownCallback(AdListenerHelper.AdNativeShownCallback adNativeShownCallback) {
        this.adNativeShownCallback = adNativeShownCallback;
    }
}
