package com.gem.media.ad;

import static com.gem.media.ad.CpAdData.CP_TOPON;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.ads.cal.picturetranslate.PictureApplication;
import com.gem.media.AdReqHasCallBackUtil;
import com.gem.media.NetworkUtils;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.AdUtils;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.AdLoadedCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.thinkup.core.api.AdError;
import com.thinkup.core.api.TUAdInfo;
import com.thinkup.core.api.TUAdStatusInfo;
import com.thinkup.interstitial.api.TUInterstitial;
import com.thinkup.interstitial.api.TUInterstitialListener;

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

public class InterstitialAdManager {
    private static final String TAG = "InterstitialAdManager";
    private long requestTime = -1;
    private InterstitialAdStatusCallBack adStatusCallBack;

    private static final class InterstitialAdManagerHolder {
        static final InterstitialAdManager adManager = new InterstitialAdManager();
    }

    public static InterstitialAdManager getInstance() {
        return InterstitialAdManagerHolder.adManager;
    }

    //注意：广告对象必须要全局引用，如果广告对象是临时变量会导致广告加载过程中有可能被回收，无法接收广告事件回调
    private TUInterstitial mInterstitialAd;

    private String sAdId;
    private String scenario;

    private void initATInterstitial() {
        if (TextUtils.isEmpty(sAdId)) {
            return;
        }
        if (null == mInterstitialAd) {
            mInterstitialAd = new TUInterstitial(PictureApplication.getApplication(), sAdId);
            mInterstitialAd.setAdListener(new TUInterstitialListener() {
                @Override
                public void onInterstitialAdLoaded() {
                    loadIndex = 0;
                    AdReqHasCallBackUtil.setValue(-1);
                    ALog.w(TAG, "--------onInterstitialAdLoaded -------    " + PictureApplication.getApplication().getPackageName()
                            + "adLoadedCallback  = " + adLoadedCallback);

                    if (adLoadedCallback != null) {
                        adLoadedCallback.onLoaded();
                    }
                    clearAdLoadedCallback();

                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adCallback) {
                        adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, "interstitial", "loaded", requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, "interstitial", "loaded", requestTime, Constants.SCENARIO_CHAPIN);
                    }
                    requestTime = System.currentTimeMillis();
                }

                @Override
                public void onInterstitialAdLoadFail(AdError adError) {
                    AdReqHasCallBackUtil.setValue(-1);
                    //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
                    //AdError，请参考 https://docs.toponad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                    ALog.e(TAG, "onInterstitialAdLoadFail:   " + adError.getFullErrorInfo() + "    " + PictureApplication.getApplication().getPackageName());
                    requestTime = System.currentTimeMillis() - requestTime;
                    String reason = "interstitial " + "code: " + adError.getCode() + " msg: " + adError.getFullErrorInfo();
                    if (null != adCallback) {
                        adCallback.onAdError(Constants.NODE_ERROR_EID, "interstitial", reason, requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onNoAdError(Constants.NODE_ERROR, "interstitial", reason, requestTime, Constants.SCENARIO_CHAPIN);
                    }
                    try {
                        loadAd(loadIndex);
                    } catch (Exception e) {
                        //
                    }
                }

                @Override
                public void onInterstitialAdClicked(TUAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdClicked     " + PictureApplication.getApplication().getPackageName());

                    if (null != adCallback) {
                        adCallback.onAdClick(Constants.NODE_CLICK_EID, "interstitial", "click", -1);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdClick(Constants.NODE_CLICK, "interstitial", "click", -1, scenario);
                    }

                }

                @Override
                public void onInterstitialAdShow(TUAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdShow     " + PictureApplication.getApplication().getPackageName()
                            +"   "+atAdInfo.getAdsourceId()
                            +"   "+atAdInfo.getChannel()
                            +"   "+atAdInfo.getSubChannel()
                            +"   "+atAdInfo.getNetworkFirmId());

                    //ATAdInfo可区分广告平台以及获取广告平台的广告位ID等
                    //请参考 https://docs.toponad.com/#/zh-cn/android/android_doc/android_sdk_callback_access?id=callback_info
                    //建议在此回调中调用load进行广告的加载，方便下一次广告的展示（不需要调用isAdReady()）
                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adCallback) {
                        adCallback.onAdShow(Constants.NODE_SHOW_EID, "interstitial", "show", requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdShow(Constants.NODE_SHOW, "interstitial", "show", requestTime, scenario);
                    }
                    AdManager.getInstance().saveAdExpCount();
                }

                @Override
                public void onInterstitialAdClose(TUAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdClose   " + PictureApplication.getApplication().getPackageName()+"  "+atAdInfo.getNetworkFirmId());
                    if (null != adCallback) {
                        adCallback.onAdClose(Constants.NODE_CLOSE_EID, "interstitial", "close type: " + atAdInfo.getDismissType(), -1);
                        adCallback = null;
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, "interstitial", "close type: " + atAdInfo.getDismissType(), -1, scenario);
                    }
                    clearAdLoadedCallback();
                    loadAd();

                }

                @Override
                public void onInterstitialAdVideoStart(TUAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdVideoStart:    " + PictureApplication.getApplication().getPackageName()+"   "+atAdInfo.getNetworkFirmId());

                    if (null != adStatusCallBack) {
                        adStatusCallBack.onInterstitialAdVideoStart(Constants.NODE_INTERSTITIAL_AD_VIDEO_START, "interstitial", "start video", -1, scenario);
                    }
                }

                @Override
                public void onInterstitialAdVideoEnd(TUAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdVideoEnd:    " + PictureApplication.getApplication().getPackageName());
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onInterstitialAdVideoEnd(Constants.NODE_INTERSTITIAL_AD_VIDEO_END, "interstitial", "end video", -1, scenario);
                    }
                }

                @Override
                public void onInterstitialAdVideoError(AdError adError) {
                    //AdError，请参考 https://docs.toponad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                    ALog.w(TAG, "onInterstitialAdVideoError:" + adError.getFullErrorInfo());
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onInterstitialAdVideoError(Constants.NODE_INTERSTITIAL_AD_VIDEO_ERROR, "interstitial", "error video: " + adError.getFullErrorInfo(), -1, scenario);
                    }
                }
            });
        }
    }

    public int loadAd() {
        //        Map<String, String> map = new HashMap<>();
//        map.put("status", String.valueOf(status));
//        map.put("type", "interstitial");
//        StatsStaticHelper.onEvent(Constants.NODE_AD_REQ_STATUS, map);
        return loadAd(loadIndex);
    }

    private volatile long lastAdRequestTime = 0;
    private static final long MIN_REQUEST_INTERVAL = 200;
    public int loadIndex = 0;

    public int loadAd(String adId) {
        // 检查初始化状态
        if (!CpAdData.adInitSuccess) {
            return -11;
        }
        ALog.w(TAG, " mInterstitialAd  start load");
        if (mInterstitialAd != null) {
            // 5. 检查广告状态
            TUAdStatusInfo status = mInterstitialAd.checkAdStatus();
            ALog.w(TAG, "status = " +status);
            // 6. 处理不同状态
            if (status.isReady()) {
                ALog.w(TAG, "mInterstitialAd is Ready");
                return 0;
            }
            if (status.isLoading()) {
                return -10;
            }
        }
        if (!canRequestAd()) {
            return -8;
        }
        sAdId = adId;
        if (TextUtils.isEmpty(sAdId)) {
            AdData adData = CpAdData.getInstance().getAdData(CP_TOPON);
            if (adData == null) {
                ALog.w(TAG, "   sAdId  get  adData == null");
                return -2;
            }
            sAdId = adData.getAdAdId(AdData.AD_TYPE_INTERSTITIAL, loadIndex);
        }
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w(TAG, "   sAdId  is null ");
            this.loadIndex = 0;
            return -1;
        }
        if (mInterstitialAd != null && !sAdId.equals(mInterstitialAd.mPlacementId)) {
            mInterstitialAd = null;
        }
        if (ensureAdInitialized()) {
            ALog.w(TAG, "   mInterstitialAd   ==  null" + "   " + PictureApplication.getApplication().getPackageName());
            return -3;
        }
        executeAdLoad();
        return 1;
    }

    private int loadAd(int loadIndex) {
        // 检查初始化状态
        if (!CpAdData.adInitSuccess) {
            return -11;
        }
        ALog.w(TAG, " mInterstitialAd  start load");
        if (mInterstitialAd != null) {
            // 5. 检查广告状态
            TUAdStatusInfo status = mInterstitialAd.checkAdStatus();
            ALog.w(TAG, "status = " +status);
            // 6. 处理不同状态
            if (status.isReady()) {
                ALog.w(TAG, "mInterstitialAd is Ready");
                return 0;
            }
            if (status.isLoading()) {
                return -10;
            }
        }
        if (!canRequestAd()) {
            return -8;
        }
        AdData adData = CpAdData.getInstance().getAdData(CP_TOPON);
        if (adData == null) {
            ALog.w(TAG, "   sAdId  get  adData == null");
            return -2;
        }
        sAdId = adData.getAdAdId(AdData.AD_TYPE_INTERSTITIAL, loadIndex);
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w(TAG, "   sAdId  is null ");
            this.loadIndex = 0;
            return -1;
        }
        if (mInterstitialAd != null && !sAdId.equals(mInterstitialAd.mPlacementId)) {
            mInterstitialAd = null;
        }

        if (ensureAdInitialized()) {
            ALog.w(TAG, "   mInterstitialAd   ==  null" + "   " + PictureApplication.getApplication().getPackageName());
            return -3;
        }

        // 7. 执行广告加载
        this.loadIndex = loadIndex + 1;
        executeAdLoad();
        return 1;
    }

    private boolean ensureAdInitialized() {
        if (mInterstitialAd == null) {
            initATInterstitial();
        }
        return mInterstitialAd == null;
    }

    private boolean canRequestAd() {
        // 检查请求间隔
        long currentTime = System.currentTimeMillis();
        if (Math.abs(currentTime - lastAdRequestTime) < MIN_REQUEST_INTERVAL) {
            return false;
        }

        // 检查是否允许请求
        if (!AdManager.getInstance().isCanNextAdRequest()) {
            return false;
        }

        lastAdRequestTime = currentTime;
        return true;
    }

    private void executeAdLoad() {
        mInterstitialAd.load();
        // 记录请求时间
        AdReqHasCallBackUtil.setValue(System.currentTimeMillis());
        requestTime = System.currentTimeMillis();
        // 回调通知
        if (adStatusCallBack != null) {
            adStatusCallBack.onAdLoad(Constants.NODE_REQUEST, "interstitial", "load", -1, Constants.SCENARIO_CHAPIN);
        }

        ALog.w(TAG, "mInterstitialAd end load");
    }

    public void showAd(Activity activity, String scenario) {
        if (!AdUtils.getInstance().enableShowAd()) {
            if (activity.isFinishing() || activity.isDestroyed()) {
                return;
            }
        }
        if (!TextUtils.isEmpty(sAdId)) {
            TUInterstitial.entryAdScenario(sAdId, "f65bf35b235ce0");
        }
        this.scenario = scenario;
        if (null != mInterstitialAd && mInterstitialAd.isAdReady()) {
            mInterstitialAd.show(activity, "f65bf35b235ce0");
        }
    }

    public boolean hasCache() {
        return null != mInterstitialAd && mInterstitialAd.isAdReady();
    }

    public boolean isLoading() {
        if (null == mInterstitialAd) {
            return false;
        }
        TUAdStatusInfo atAdStatusInfo = mInterstitialAd.checkAdStatus();
        if (atAdStatusInfo == null) {
            return false;
        }
        return atAdStatusInfo.isLoading();
    }

    private AdLoadedCallback adLoadedCallback;
    private AdCallback adCallback;

    public void setAdCallback(AdCallback adCallback) {
        this.adCallback = adCallback;
    }

    public void setAdLoadedCallback(AdLoadedCallback adLoadedCallback) {
        ALog.w(TAG, "   setAdCallback --->    " + adLoadedCallback);
        this.adLoadedCallback = adLoadedCallback;
    }

    public void clearAdLoadedCallback() {
        adLoadedCallback = null;
    }

    public void setAdStatusCallBack(InterstitialAdStatusCallBack adStatusCallBack) {
        this.adStatusCallBack = adStatusCallBack;
    }

}
