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.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 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 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 TUInterstitial mInterstitialAd;

    private static String sAdId;

    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() {
                    AdReqHasCallBackUtil.setValue(-1);
                    ALog.w(TAG, "--------onInterstitialAdLoaded -------    " + PictureApplication.getApplication().getPackageName());

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

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

                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdClick(Constants.NODE_CLICK, "half_interstitial", "click", -1, Constants.SCENARIO_4);
                    }

                }

                @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 != adStatusCallBack) {
                        adStatusCallBack.onAdShow(Constants.NODE_SHOW, "half_interstitial", "show", requestTime, Constants.SCENARIO_4);
                    }
                }

                @Override
                public void onInterstitialAdClose(TUAdInfo atAdInfo) {
                    ALog.w(TAG, "onInterstitialAdClose   " + PictureApplication.getApplication().getPackageName()+"  "+atAdInfo.getNetworkFirmId());
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, "half_interstitial", "close type: " + atAdInfo.getDismissType(), -1, Constants.SCENARIO_4);
                    }
                    NativeAdWindManager.getInstance().removeNativeAd();
                    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, "half_interstitial", "start video", -1, Constants.SCENARIO_4);
                    }
                }

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

                @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, Constants.SCENARIO_4);
                    }
                }
            });
        }
    }

    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) {
            ALog.w(TAG, " canLoadAdData  half_interstitial   ==  false");
            return -2;
        }

        if (mInterstitialAd == null) {
            initATInterstitial();
        }
        if (mInterstitialAd == null) {
            ALog.w(TAG, "   half_interstitial   ==  null" + "   " + PictureApplication.getApplication().getPackageName());
            return -3;
        }
        TUAdStatusInfo 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(PictureApplication.getApplication())) {
//                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, Constants.SCENARIO_4);
            }
            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)) {
            TUInterstitial.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);
    }


}
