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.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATAdStatusInfo;
import com.anythink.core.api.AdError;
import com.anythink.interstitial.api.ATInterstitial;
import com.anythink.interstitial.api.ATInterstitialListener;
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 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 static ATInterstitial mInterstitialAd;

    private static String sAdId;

    private void initATInterstitial() {
        if (TextUtils.isEmpty(sAdId)) {
            return;
        }
        if (null == mInterstitialAd) {
            mInterstitialAd = new ATInterstitial(PictureApplication.getApplication(), sAdId);
            mInterstitialAd.setAdListener(new ATInterstitialListener() {
                @Override
                public void onInterstitialAdLoaded() {
                    AdReqHasCallBackUtil.setValue(-1);
                    ALog.w(TAG, "--------onInterstitialAdLoaded -------    "
                            + "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);
                    }
                    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() + "    " );
                    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);
                    }
                }

                @Override
                public void onInterstitialAdClicked(ATAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdClicked     " );

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

                }

                @Override
                public void onInterstitialAdShow(ATAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdShow     "
                            +"   "+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);
                    }
                    AdManager.getInstance().saveAdExpCount();
                }

                @Override
                public void onInterstitialAdClose(ATAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdClose   " +"  "+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);
                    }
                    clearAdLoadedCallback();
                    loadAd();

                }

                @Override
                public void onInterstitialAdVideoStart(ATAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdVideoStart:    " +"   "+atAdInfo.getNetworkFirmId());

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

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

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

    public int loadAd(String sAdId) {
        InterstitialAdManager.sAdId = sAdId;
        int status = 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 status;
    }

    private volatile long lastAdRequestTime = 0;
    private static final long MIN_REQUEST_INTERVAL = 1000;

    private int loadAd() {
        ALog.w(TAG, " mInterstitialAd  start load");
        AdData adData = CpAdData.getInstance().getAdData(CP_TOPON);
        if (adData == null) {
            ALog.w(TAG, "   sAdId  get  adData == null");
        }
        if (TextUtils.isEmpty(sAdId) && null != adData) {
            sAdId = adData.getAdAdId(AdData.AD_TYPE_INTERSTITIAL);
        }
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w(TAG, "   sAdId  is null ");
            return -1;
        }

        if (null != adData && !adData.canLoadAdData(AdData.AD_TYPE_INTERSTITIAL)) {
            ALog.w(TAG, " canLoadAdData  mInterstitialAd   ==  false");
            return -2;
        }

        if (mInterstitialAd == null) {
            initATInterstitial();
        }
        if (mInterstitialAd == null) {
            ALog.w(TAG, "   mInterstitialAd   ==  null" + "   " );
            return -3;
        }
        ATAdStatusInfo atAdStatusInfo = mInterstitialAd.checkAdStatus();
        ALog.w(TAG, "mInterstitialAd  atAdStatusInfo: " + atAdStatusInfo+"   "+mInterstitialAd);
        if (atAdStatusInfo.isReady()) {
            ALog.w(TAG, "mInterstitialAd is Ready");
        } else if (!atAdStatusInfo.isLoading()) {
            long currentTime = System.currentTimeMillis();
            if (Math.abs(currentTime - lastAdRequestTime) < MIN_REQUEST_INTERVAL) {
                return -8;
            }
            lastAdRequestTime = currentTime;
            if (!AdManager.getInstance().isCanNextAdRequest()) {
                return -4;
            }
//            if (!NetworkUtils.isConnected(A.getContext())) {
//                return -5;
//            }
            if (!CpAdData.adInitSuccess) {
                return -6;
            }
            mInterstitialAd.load();
            AdReqHasCallBackUtil.setValue(System.currentTimeMillis());
            requestTime = System.currentTimeMillis();
            if (null != adStatusCallBack) {
                adStatusCallBack.onAdLoad(Constants.NODE_REQUEST, "interstitial", "load", -1);
            }
            ALog.w(TAG, "mInterstitialAd end load");
            return 1;
        } else {
            ALog.w(TAG, "mInterstitialAd is loading");
            return -7;
        }
        return 0;
    }

    public void showAd(Activity activity) {
        if (!AdUtils.getInstance().enableShowAd()) {
            if (activity.isFinishing() || activity.isDestroyed()) {
                return;
            }
//            Context context = A.getContext();
//            if (context instanceof A) {
//                if (((A)context).activityIsClose()) {
//                    return;
//                }
//            }
        }
        if (!TextUtils.isEmpty(sAdId)) {
            ATInterstitial.entryAdScenario(sAdId, "f65bf35b235ce0");
        }
        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;
        }
        ATAdStatusInfo 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;
    }

    public static void setsAdId(String sAdId) {
        InterstitialAdManager.sAdId = sAdId;
    }

    public static String getsAdId() {
        return sAdId;
    }

    public static boolean adIdIsNullOrEmpty() {
        return TextUtils.isEmpty(sAdId);
    }


}
