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 android.view.ViewGroup;

import com.ads.cal.picturetranslate.PictureApplication;
import com.gem.media.NetworkUtils;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.AdUtils;
import com.gem.media.splash.base.protocol.AdLoadedCallback;
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.thinkup.core.api.AdError;
import com.thinkup.core.api.TUAdConst;
import com.thinkup.core.api.TUAdInfo;
import com.thinkup.core.api.TUAdStatusInfo;
import com.thinkup.core.api.TUNetworkConfirmInfo;
import com.thinkup.splashad.api.TUSplashAd;
import com.thinkup.splashad.api.TUSplashAdExtraInfo;
import com.thinkup.splashad.api.TUSplashExListener;

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


public class OpenAdManager {
    private TUSplashAd splashAd;
    private AdLoadedCallback adLoadedCallback;
    private AdCallback adCallback;
    private long requestTime;
    private AdStatusCallBack adStatusCallBack;

    private static final class OpenAdManagerHolder {
        static final OpenAdManager adManager = new OpenAdManager();
    }

    public static OpenAdManager getInstance() {
        return OpenAdManager.OpenAdManagerHolder.adManager;
    }

    public void setAdLoadedCallback(AdLoadedCallback adLoadedCallback) {
        this.adLoadedCallback = adLoadedCallback;
    }

    public void clearAdLoadedCallback() {
        adLoadedCallback = null;
    }

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

    private static String sAdId;

    private void initSplashAd() {
        if (TextUtils.isEmpty(sAdId)) {
            return;
        }
        if (splashAd == null) {
            TUSplashExListener listener = new TUSplashExListener() {
                @Override
                public void onDeeplinkCallback(TUAdInfo atAdInfo, boolean b) {

                }

                @Override
                public void onDownloadConfirm(Context context, TUAdInfo atAdInfo, TUNetworkConfirmInfo atNetworkConfirmInfo) {

                }

                @Override
                public void onAdLoaded(boolean isTimeout) {

                    ALog.w("GEM_WZ", "open onAdLoaded   " + isTimeout + "       ");
                    //加载未超时时
                    if (!isTimeout) {

                    }

                    if (null != adLoadedCallback) {
                        adLoadedCallback.onLoaded();
                    }
                    clearAdLoadedCallback();
                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adCallback) {
                        adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, "open", "loaded", requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, "open", "loaded", requestTime);
                    }

                }

                @Override
                public void onAdLoadTimeout() {
                    //加载超时后，直接进入主界面
                    ALog.w("GEM_WZ", "open onAdLoadTimeout   " );
                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adCallback) {
                        adCallback.onAdTimeOut(Constants.NODE_ERROR_EID, "open", "timeout", requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdLoadTimeout(Constants.NODE_ERROR, "open", "timeout", requestTime);
                    }

                }

                @Override
                public void onNoAdError(AdError adError) {
                    //加载失败直接进入主界面
                    ALog.w("GEM_WZ", "open onNoAdError   " + adError.getFullErrorInfo() + "         " );

                    requestTime = System.currentTimeMillis() - requestTime;
                    String reason = "open " + "code: " + adError.getCode() + " msg: " + adError.getFullErrorInfo();
                    if (null != adCallback) {
                        adCallback.onAdError(Constants.NODE_ERROR_EID, "open", reason, requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onNoAdError(Constants.NODE_ERROR, "open", reason, requestTime);
                    }
                }

                @Override
                public void onAdShow(TUAdInfo entity) {
                    ALog.w("GEM_WZ", "open OpenonAdShow   ");


                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adCallback) {
                        adCallback.onAdShow(Constants.NODE_SHOW_EID, "open", "show", requestTime);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdShow(Constants.NODE_SHOW, "open", "show", requestTime);
                    }
                    clearAdLoadedCallback();
                    AdManager.getInstance().saveAdExpCount();
                }

                @Override
                public void onAdClick(TUAdInfo atAdInfo) {
                    ALog.w("GEM_WZ", "open onAdClick   " );
                    if (null != adCallback) {
                        adCallback.onAdClick(Constants.NODE_CLICK_EID, "open", "click", -1);
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdClick(Constants.NODE_CLICK, "open", "click", -1);
                    }

                }

                @Override
                public void onAdDismiss(TUAdInfo entity, TUSplashAdExtraInfo splashAdExtraInfo) {
                    ALog.w("GEM_WZ", "open onAdDismiss   " );
                    if (null != adCallback) {
                        adCallback.onAdClose(Constants.NODE_CLOSE_EID, "open", "close type: " + splashAdExtraInfo.getDismissType(), -1);
                        adCallback = null;
                    }
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, "open", "close type: " + splashAdExtraInfo.getDismissType(), -1);
                    }
                    //=1无区分 =2跳过结束 =3倒计时结束 =4点击广告结束 =99开屏展示失败
                    if (splashAdExtraInfo.getDismissType() == TUAdConst.DISMISS_TYPE.SHOWFAILED) {
                    }
                    //开屏广告展示关闭后进入主界面
                    //注意：部分平台跳转落地页后倒计时不暂停，即使在看落地页，倒计时结束后仍然会回调onAdDismiss
                    //因此在页面跳转时需要特殊处理，详情参考下方示例代码


                }
            };

            //设置首次开屏广告广告源，请从TopOn后台兜底开屏广告源导出配置

            //b1f138leh1o4gp
            splashAd = new TUSplashAd(PictureApplication.getApplication(), sAdId, listener, 5000, null);
        }
    }


    private long lastAdRequestTime = 0;
    private static final long MIN_REQUEST_INTERVAL = 3 * 1000;

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

    private int loadAd() {
        ALog.w("GEM_WZ", " open  start load");

        AdData adData = CpAdData.getInstance().getAdData(CP_TOPON);
        if (adData == null) {
            ALog.w("GEM_WZ", "open   sAdId  get  adData == null");
        }
        if (TextUtils.isEmpty(sAdId) && null != adData) {
            sAdId = adData.getAdAdId(AdData.AD_TYPE_OPEN);
        }
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w("GEM_WZ", "open   sAdId  is null ");
            return -1;
        }

        if (null != adData && !adData.canLoadAdData(AdData.AD_TYPE_OPEN)) {
            ALog.w("GEM_WZ", " canLoadAdData  open   ==  false");
            return -2;
        }

        if (null == splashAd) {
            initSplashAd();
        }
        ALog.w("GEM_WZ", "open load   splashAd  " + splashAd);
        if (splashAd == null) {
            return -3;
        }

        TUAdStatusInfo atAdStatusInfo = splashAd.checkAdStatus();
        ALog.w("GEM_WZ", "open   atAdStatusInfo: " + atAdStatusInfo);
        if (atAdStatusInfo.isReady()) {
            ALog.w("GEM_WZ", "open is Ready");
        } else if (!atAdStatusInfo.isLoading()) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastAdRequestTime < MIN_REQUEST_INTERVAL) {
                return -8;
            }
            lastAdRequestTime = currentTime;
            if (!AdManager.getInstance().isCanNextAdRequest()) {
                return -4;
            }
//            if (!NetworkUtils.isConnected(A.getContext())) {
//                StatsStaticHelper.onEvent(Constants.NODE_AD_REQ_NOT_NET, "open");
//                return -5;
//            }
            if (!CpAdData.adInitSuccess) {
                StatsStaticHelper.onEvent(Constants.NODE_AD_NOT_INIT, "open");
                return -6;
            }
            StatsStaticHelper.onEvent(Constants.NODE_AD_REQ_NET, "open");
            splashAd.loadAd();
            requestTime = System.currentTimeMillis();
            if (null != adStatusCallBack) {
                adStatusCallBack.onAdLoad(Constants.NODE_REQUEST, "open", "load", -1);
            }
            ALog.w("GEM_WZ", "open end load");
            return 1;
        } else {
            ALog.w("GEM_WZ", "open is loading");
        }
        return 0;

    }

    public void showAd(Activity activity, ViewGroup viewGroup) {
        if (!AdUtils.getInstance().enableShowAd()) {
            if (activity.isFinishing() || activity.isDestroyed()) {
                return;
            }
        }
        if (!TextUtils.isEmpty(sAdId)) {
            TUSplashAd.entryAdScenario(sAdId, "f65bf35e68ddf9");
        }
        if (null != splashAd && splashAd.isAdReady()) {
            splashAd.show(activity, viewGroup, "f65bf35e68ddf9");
        }
    }

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

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

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

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

    public static String getsAdId() {
        return sAdId;
    }

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

}
