package com.gem.media.ad;

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

import android.app.Activity;
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.NativeAdWindManager;
import com.gem.media.NetworkUtils;
import com.gem.media.StatsStaticHelper;
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 InterstitialHalfAdManager {
    private static final String TAG = "InterstitialAdManager";
    private long requestTime = -1;
    private InterstitialAdStatusCallBack adStatusCallBack;

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

    public static InterstitialHalfAdManager 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 -------    ");

                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, "half_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 != adStatusCallBack) {
                        adStatusCallBack.onNoAdError(Constants.NODE_ERROR, "half_interstitial", reason, requestTime);
                    }
                }

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

                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdClick(Constants.NODE_CLICK, "half_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 != adStatusCallBack) {
                        adStatusCallBack.onAdShow(Constants.NODE_SHOW, "half_interstitial", "show", requestTime);
                    }
                }

                @Override
                public void onInterstitialAdClose(ATAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdClose   "+"  "+atAdInfo.getNetworkFirmId());
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, "half_interstitial", "close type: " + atAdInfo.getDismissType(), -1);
                    }
                    NativeAdWindManager.getInstance().removeNativeAd();
                    loadAd();

                }

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

                    if (null != adStatusCallBack) {
                        adStatusCallBack.onInterstitialAdVideoStart(Constants.NODE_INTERSTITIAL_AD_VIDEO_START, "half_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, "half_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, "half_interstitial", "error video: " + adError.getFullErrorInfo(), -1);
                    }
                }
            });
        }
    }

    public int loadAd(String sAdId) {
        InterstitialHalfAdManager.sAdId = sAdId;
        int status = loadAd();
        Map<String, String> map = new HashMap<>();
        map.put("status", String.valueOf(status));
        map.put("type", "half_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, " half_interstitial  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_HALF_INTERSTITIAL);
        }
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w(TAG, "   sAdId  is null ");
            return -1;
        }

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

        if (mInterstitialAd == null) {
            initATInterstitial();
        }
        if (mInterstitialAd == null) {
            ALog.w(TAG, "   half_interstitial   ==  null" + "   ");
            return -3;
        }
        ATAdStatusInfo atAdStatusInfo = mInterstitialAd.checkAdStatus();
        ALog.w(TAG, "half_interstitial  atAdStatusInfo: " + atAdStatusInfo+"   "+mInterstitialAd);
        if (atAdStatusInfo.isReady()) {
            ALog.w(TAG, "half_interstitial 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, "half_interstitial", "load", -1);
            }
            ALog.w(TAG, "half_interstitial end load");
            return 1;
        } else {
            ALog.w(TAG, "half_interstitial is loading");
            return -7;
        }
        return 0;
    }

    public void reload() {
        loadAd();
    }

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

    public void showAd(Activity activity) {
        if (activity.isFinishing() || activity.isDestroyed()) {
            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 void setAdStatusCallBack(InterstitialAdStatusCallBack adStatusCallBack) {
        this.adStatusCallBack = adStatusCallBack;
    }

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

    public static String getsAdId() {
        return sAdId;
    }

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


}
