package com.gem.media;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
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 com.ads.cal.notes.BaseApplication;
import com.ads.cal.notes.MainActivity;
import com.ads.cal.notes.TActivity;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PkgUtils;
import com.gem.media.util.SplashWindowViewManger;
import com.or.ange.dot.utils.LLog;

import org.json.JSONObject;

import java.lang.ref.WeakReference;

public class ShowHomeAdUtil {
    private static final String TAG = "ShowHomeAdUtil";
    protected static final String CV_PKG = "cv_pkg";
    protected static final String NODE = "node";
    protected static final String MESSENGER = "messenger";
    protected static final String APP_ID = "appid";
    protected static final String T = "_";
    protected static final String BG = "bg";
    protected static final String INTERSTITIAL = "interstitial";
    protected final String a_er = "a_er";

    protected Node node;

    protected final Handler handler = new Handler();
    private HandlerThread asyncHandlerThread;
    private static final String ASYNC_THREAD_2 = "async_thread_2";



    private HandlerThread getAsyncHandlerThread() {
        if (null == asyncHandlerThread) {
            asyncHandlerThread = new HandlerThread(ASYNC_THREAD_2);
            asyncHandlerThread.start();
        }
        return asyncHandlerThread;
    }

    private Handler asyncHandler;

    protected static final String VN = "vn";
    protected static final String VC = "vc";
    protected String appVersionName;
    protected String appVersionCode;
    protected Messenger messenger;

    protected boolean isFinished = false;
    protected String cvPkg;
    protected Intent intent;
    protected static final String CLOSE_TIME = "close_time";

    
    public void init(Activity context) {
        try {
            Window window = context.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        } catch (Exception e) {
            //
        }
        if (null == asyncHandler) {
            Looper looper = getAsyncHandlerThread().getLooper();
            if (null != looper) {
                asyncHandler = new Handler(looper);
            }
        }
        try {
            intent = context.getIntent();
        } catch (Exception e) {
            //
        }
        initAdCallBack(context);
        initData(context);
        ALog.d(TAG, "onCreate");
    }
    
    public void start(Activity activity) {
        boolean show = setShowSplashWindow(activity, cvPkg, intent);
        boolean cache = AdManager.getInstance().hasCache();
        report("ditu_s", "show = " + show + " cache = " + cache );
        ALog.d(TAG, "show = " + show + " cache = " + cache);
        if (show || cache) {
            if (isFinished || activity.isFinishing()) {
                report("ons_f", "finish");
                return;
            }
            statPageShow(activity);
            showAd(activity);
        } else {
            clearMsg();
        }
    }

    private boolean setShowSplashWindow(Activity activity, String cvPkg, Intent intent) {
        String bgPath = null;
        long closeTime = 5000;
        if (null != intent) {
            bgPath = intent.getStringExtra(BG);
            closeTime = intent.getLongExtra(CLOSE_TIME, 5000);
        }
        if (!SplashWindowViewManger.getInstance().isWindowShowing()) {
            SplashWindowViewManger.getInstance().showSplashWindowView(cvPkg, bgPath, closeTime);
        }
        if (!SplashWindowViewManger.getInstance().isWindowShowing()) {
            report("nobg", "");
            return false;
        }
        ALog.d(TAG, "--------closeTime " + closeTime);
        SplashWindowViewManger.getInstance().stopRemoveSplashWindowView();
        handler.postDelayed(getFinishRunnable(activity), closeTime);
        return true;
    }

    private Runnable getFinishRunnable(Activity activity) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    activity.finish();
                } catch (Exception e) {

                }
            }
        };
    }

    public void clearMsg() {
        handler.removeCallbacksAndMessages(null);
    }

    public void destroy() {
        isFinished = false;
        clearMsg();
    }

    private void initData(Activity activity) {
        if (null != intent) {
            initSource(intent, activity);
            try {
                node = intent.getParcelableExtra(NODE);
            } catch (Exception e) {
                //
            }
        }
    }

    public void stop(Activity activity) {
        if (!isFinished) {
            try {
                activity.finish();
            } catch (Exception e) {
                //
            }
        }
    }


    private void showAd(Activity activity) {
        if (AdmobInterstitialManager.instance().isAdAvailable()) {
            clearMsg();
            AdmobInterstitialManager.instance().showAd(activity, Constants.SCENARIO_CHAPIN_PROCESS);
            report(Constants.NODE_CACHE, INTERSTITIAL);
        } else {
            LLog.d(TAG, "showAd" + 7);
            activity.finish();
        }
    }

    private void statPageShow(Activity a) {
        Event event = new Event();
        event.type = Constants.NODE_PAGE_SHOW;
        event.reason = a.getPackageName();
        addNodeEvent(event);
    }

    private void report(String type, String reason) {
        Event event = new Event();
        event.type = type;
        event.reason = reason;
        addNodeEvent(event);
    }

    private void initAdCallBack(Activity activity) {
        if (activity instanceof MainActivity) {
            AdmobInterstitialManager.instance().setAdCallback(new InterstitialAdCallback((MainActivity) activity));
        }
    }


    private void initSource(Intent intent, Activity a) {
        try {
            String cvPkg = intent.getStringExtra(CV_PKG);
            InitA.getInstance().setCvPkg(cvPkg);
            this.cvPkg = cvPkg;
            try {
                messenger = intent.getParcelableExtra(MESSENGER);
            } catch (Exception e) {
                //
            }
            report("ditu_s", "messenger = " + messenger + " node = " + node );
            String adAppId_channelId = intent.getStringExtra(APP_ID);
            LLog.w(TAG, "initSource  adAppId_channelId " + adAppId_channelId);

            if (!TextUtils.isEmpty(adAppId_channelId)) {
                String channelId = null;

                if (adAppId_channelId.contains(T)) {
                    String[] s = adAppId_channelId.split(T);
                    if (s.length > 1) {
                        channelId = s[1];
                    }
                }

                if (TextUtils.isEmpty(channelId)) {
                    channelId = InitA.DEFAULT_APP_ID;
                }

                InitA.getInstance().initMediaApp(channelId);
            } else {
                InitA.getInstance().initMediaApp(InitA.DEFAULT_APP_ID);
            }
        } catch (Throwable throwable) {
            LLog.d(TAG, throwable.getMessage());
            StatsStaticHelper.reportOnEvent(a_er, Log.getStackTraceString(throwable));
            a.finish();
        }
    }

    private void sendAdShowMessage() {
        clearMsg();
    }
    
    public void finishs() {
        LLog.e(TAG, "finishs: " + isFinished);
        if (isFinished) {
            return;
        }
        isFinished = true;
        try {
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 46;
                Bundle bundle = new Bundle();
                if (node != null) {
                    bundle.putParcelable("node", node);
                }
                message.setData(bundle);
                messenger.send(message);
                LLog.e(TAG, "finishs: 11111111111  node "+node );
            }
        } catch (Throwable throwable) {
            LLog.e(TAG, "finish e: " + Log.getStackTraceString(throwable));
        } 
    }


    private void addNodeEvent(Event event) {
        if (node != null) {
            try {
                JSONObject reason = new JSONObject();
                reason.put(Constants.TARGET_PKG, cvPkg);
                reason.put(Constants.MEDIA_PKG, BaseApplication.getApplication().getPackageName());
                reason.put(Constants.REASON, event.reason);
                if (TextUtils.isEmpty(appVersionName)) {
                    appVersionName = PkgUtils.getAppVersionName(BaseApplication.getApplication(), BaseApplication.getApplication().getPackageName());
                }
                if (TextUtils.isEmpty(appVersionCode)) {
                    appVersionCode = PkgUtils.getAppVersionCode(BaseApplication.getApplication(), BaseApplication.getApplication().getPackageName());
                }
                reason.put(VN, appVersionName);
                reason.put(VC, appVersionCode);
                event.reason = reason.toString();
            } catch (Exception e) {
            }
            node.addEvent(event);
        }
    }

    private static class InterstitialAdCallback implements AdCallback {

        private final WeakReference<MainActivity> weakReference;

        public InterstitialAdCallback(MainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        private void report(String type, String reason) {
            MainActivity jojowdDays14 = weakReference.get();
            if (jojowdDays14 != null) {
                ShowHomeAdUtil showHomeAdUtil = jojowdDays14.getShowHomeAdUtil();
                if (null != showHomeAdUtil) {
                    showHomeAdUtil.report(type, reason);
                }
            }
        }

        private void sendAdShowMessage() {
            MainActivity jojowdDays14 = weakReference.get();
            if (jojowdDays14 != null) {
                ShowHomeAdUtil showHomeAdUtil = jojowdDays14.getShowHomeAdUtil();
                if (null != showHomeAdUtil) {
                    showHomeAdUtil.sendAdShowMessage();
                }
            }
        }

        @Override
        public void onAdLoaded(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdShow(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            SplashWindowViewManger.getInstance().removeSplashWindowView(9);
            sendAdShowMessage();
        }

        @Override
        public void onAdError(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClick(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClose(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            LLog.w(TAG, "Interstitial close    ");
            Activity a = weakReference.get();
            if (a == null) {
                InitA.getInstance().cleanTask(BaseApplication.getApplication());
                return;
            }

            try {
                a.startActivity(new Intent(a, TActivity.class));
            } catch (Exception e) {
                //
            }
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            a.finish();
        }

        @Override
        public void onAdTimeOut(String type, String ad_type, String reason, long time) {

        }
    }
}
