package com.gem.media.ad;

import android.app.KeyguardManager;
import android.content.Context;
import android.os.PowerManager;
import android.text.TextUtils;

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 java.util.Date;
import com.adsurge.adn.ads.AdConfig;
import com.adsurge.adn.ads.AdSurgeAd;
import com.adsurge.adn.ads.AdSurgeAdError;
import com.adsurge.adn.ads.interstitial.InterstitialAd;
import com.adsurge.adn.ads.interstitial.InterstitialAdListener;


public class AdSurgeInterstitialManager {

    private static final String TAG = "AdSurgeInterstitialManager";
    private static final String AD_TYPE = "adsurge_chapin";


    private static final class AdManagerHolder {
        static final AdSurgeInterstitialManager adManager = new AdSurgeInterstitialManager();
    }
    public static AdSurgeInterstitialManager instance() {
        return AdManagerHolder.adManager;
    }
    private AdCallback adCallback;
    private AdStatusCallBack adStatusCallBack;
    private InterstitialAd interstitialAd;
    private volatile boolean adIsLoading;
    private long requestTime;
    private String scenario;

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

    private void loadInterstitial(Context context, String adUnitId) {
        interstitialAd = null;
        if (null != adStatusCallBack) {
            adStatusCallBack.onAdLoad(Constants.NODE_REQUEST, AD_TYPE, "load", -1, mAdUnitId, Constants.SCENARIO_CHAPIN);
        }
        ALog.d(TAG, "loadAd AdSurge chaping end. " +adUnitId);
        interstitialAd = new InterstitialAd(context, adUnitId);
        AdConfig adConfig = new AdConfig.Builder()
                .mute(AdConfig.SoundState.MUTED)
                .build();
        requestTime = System.currentTimeMillis();
        adIsLoading = true;
        interstitialAd.loadAd(adConfig,  new InterstitialAdListener() {
            @Override
            public void onAdLoaded(AdSurgeAd adSurgeAd) {
                ALog.i(TAG, "onAdLoaded");
                adIsLoading = false;
                loadAdTime = (new Date()).getTime();
                requestTime = System.currentTimeMillis() - requestTime;
                if (null != adCallback) {
                    adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, AD_TYPE, "loaded", requestTime);
                }
                if (null != adStatusCallBack) {
                    adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, AD_TYPE, "loaded", requestTime, mAdUnitId, Constants.SCENARIO_CHAPIN);
                }
                requestTime =  System.currentTimeMillis();
                loadIndex = 0;
            }

            @Override
            public void onAdFailed(AdSurgeAdError adSurgeAdError) {
                ALog.i(TAG, adSurgeAdError.getErrorMsg());
                adIsLoading = false;
                interstitialAd = null;
                String error =
                        String.format(
                                java.util.Locale.US,
                                "code: %d, message: %s",
                                adSurgeAdError.getErrorCode(),
                                adSurgeAdError.getErrorMsg());
                ALog.i(TAG, "onAdFailedToLoad() with error: " + error + adUnitId);
                requestTime = System.currentTimeMillis() - requestTime;
                if (null != adCallback) {
                    adCallback.onAdError(Constants.NODE_ERROR_EID, AD_TYPE, error, requestTime);
                }
                if (null != adStatusCallBack) {
                    adStatusCallBack.onNoAdError(Constants.NODE_ERROR, AD_TYPE, error, requestTime, mAdUnitId, Constants.SCENARIO_CHAPIN);
                }
                loadAd(context, loadIndex);
            }

            @Override
            public void onAdImpression(AdSurgeAd adSurgeAd) {
                ALog.d(TAG, "onAdImpression.");
                requestTime = System.currentTimeMillis() - requestTime;
                if (null != adCallback) {
                    adCallback.onAdShow(Constants.NODE_SHOW_EID, AD_TYPE, "show", requestTime);
                }
                if (null != adStatusCallBack) {
                    adStatusCallBack.onAdShow(Constants.NODE_SHOW, AD_TYPE, "show", requestTime, mAdUnitId, scenario);
                }
                AdManager.getInstance().saveAdExpCount();
            }

            @Override
            public void onAdClicked(AdSurgeAd adSurgeAd) {
                ALog.d(TAG, "onAdClicked.");
                if (null != adCallback) {
                    adCallback.onAdClick(Constants.NODE_CLICK_EID, AD_TYPE, "click", -1);
                }
                if (null != adStatusCallBack) {
                    adStatusCallBack.onAdClick(Constants.NODE_CLICK, AD_TYPE, "click", -1, mAdUnitId, scenario);
                }
            }

            @Override
            public void onAdDismissed(AdSurgeAd adSurgeAd) {
                interstitialAd = null;
                ALog.d(TAG, "onAdDismissedFullScreenContent.");
                if (null != adCallback) {
                    adCallback.onAdClose(Constants.NODE_CLOSE_EID, AD_TYPE, "", -1);
                    adCallback = null;
                }
                if (null != adStatusCallBack) {
                    adStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, AD_TYPE, "", -1, mAdUnitId, scenario);
                }
                interstitialAd = null;
            }
        });
    }

    /** Check if ad exists and can be shown. */
    public boolean isAdAvailable() {
        return interstitialAd != null && interstitialAd.isValid();
    }

    private long loadAdTime;

    //ca-app-pub-3940256099942544/1033173712
    private static String mAdUnitId;
    public int loadIndex = 0;

    public void showAd(String scenario) {
        ALog.d(TAG, "Will show ad.");
        this.scenario = scenario;
        try {
            interstitialAd.showAd();
        } catch (Exception e) {
            //
        }
    }

    public void loadAd(Context context, int loadIndex) {
        if (context == null) {
            if (null != adStatusCallBack) {
                adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "context is null", -2, "", Constants.SCENARIO_CHAPIN);
            }
            return;
        }
        if (null != adStatusCallBack) {
            adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "loadAd AdSurge chaping start", -2, "", Constants.SCENARIO_CHAPIN);
        }
        ALog.d(TAG, "loadAd AdSurge chaping start.");
        if (adIsLoading) {
            ALog.d(TAG, "loadAd AdSurge isLoading. "+AdSurgeInterstitialManager.mAdUnitId);
            if (null != adStatusCallBack) {
                adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "adIsLoading", -2, AdSurgeInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
            }
            return;
        }
        if (isAdAvailable()) {
            ALog.d(TAG, "loadAd AdSurge chaping 3.");
            if (null != adStatusCallBack) {
                adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "has cache", -2, AdSurgeInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
            }
            return;
        }
        try {
            AdData adData = CpAdData.getInstance().getAdData(CpAdData.CP_ADSURGE);
            if (adData == null) {
                ALog.w(TAG, " adData = null");
                if (null != adStatusCallBack) {
                    adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "adData = null", -1, "", Constants.SCENARIO_CHAPIN);
                }
                return;
            }
            AdSurgeInterstitialManager.mAdUnitId = adData.getAdAdId(AdData.AD_TYPE_INTERSTITIAL, loadIndex);
            if (TextUtils.isEmpty(AdSurgeInterstitialManager.mAdUnitId)) {
                ALog.d(TAG, "loadAd AdSurge chaping AdUnitId is empty  loadIndex = "+loadIndex);
                if (null != adStatusCallBack) {
                    adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "AdUnitId is empty loadIndex = " + loadIndex, -1, "", Constants.SCENARIO_CHAPIN);
                }
                this.loadIndex = 0;
                return;
            }
            if (isScreenLock(context)) {
                ALog.d(TAG, "loadAd AdSurge chaping 1.");
                if (null != adStatusCallBack) {
                    adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "isScreenLock", -2, AdSurgeInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
                }
                return;
            }
            if (!isScreenOn(context)) {
                ALog.d(TAG, "loadAd AdSurge chaping 2.");
                if (null != adStatusCallBack) {
                    adStatusCallBack.nextMediaAppAdReq(Constants.NODE_NEXT_MEDIA_AD_REQ, AD_TYPE, "isScreenOff", -2, AdSurgeInterstitialManager.mAdUnitId, Constants.SCENARIO_CHAPIN);
                }
                return;
            }
            this.loadIndex = loadIndex + 1;
            loadInterstitial(context, mAdUnitId);
        } catch (Exception e) {
            ALog.d(TAG, "loadAd chaping. e ----" + e.getMessage());
        }
    }

    public boolean isAdIsLoading() {
        return adIsLoading;
    }

    private boolean isScreenLock(Context context) {
        try {
            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if (km == null) return false;
            return km.inKeyguardRestrictedInputMode();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isScreenOn(Context context) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return powerManager.isInteractive();
    }
}
