package com.gem.media.ad;



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

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

import androidx.annotation.NonNull;

import com.ads.cal.notes.manager.GoogleMobileAdsConsentManager;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.crash.CountryUtil;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.or.ange.dot.utils.LLog;

import java.util.Date;

public class AdmobInterstitialManager {

    private static final String TAG = "AdmobInterstitialManager";
    private static final String AD_TYPE = "admob_chapin";


    private static final class AdManagerHolder {
        static final AdmobInterstitialManager adManager = new AdmobInterstitialManager();
    }
    public static AdmobInterstitialManager 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);
        }
        LLog.d(TAG, "loadAd admob chaping end. " +adUnitId);
        AdRequest adRequest = new AdRequest.Builder().build();
        requestTime = System.currentTimeMillis();
        adIsLoading = true;
        InterstitialAd.load(context, adUnitId, adRequest, new InterstitialAdLoadCallback() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                LLog.i(TAG, loadAdError.getMessage());
                adIsLoading = false;
                interstitialAd = null;
                String error =
                        String.format(
                                java.util.Locale.US,
                                "domain: %s, code: %d, message: %s",
                                loadAdError.getDomain(),
                                loadAdError.getCode(),
                                loadAdError.getMessage());
                LLog.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 onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                super.onAdLoaded(interstitialAd);
                LLog.i(TAG, "onAdLoaded");
                AdmobInterstitialManager.this.interstitialAd = interstitialAd;;
                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;
            }

        });
    }

    private void setFullScreenContentCallback() {
        if (interstitialAd == null) {
            return;
        }
        interstitialAd.setFullScreenContentCallback(
                new FullScreenContentCallback() {

                    @Override
                    public void onAdClicked() {
                        super.onAdClicked();
                        LLog.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 onAdImpression() {
                        super.onAdImpression();
                        LLog.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 onAdDismissedFullScreenContent() {
                        // Called when fullscreen content is dismissed.
                        // Make sure to set your reference to null so you don't
                        // show it a second time.
                        interstitialAd = null;
                        LLog.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);
                        }
                    }

                    @Override
                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                        // Called when fullscreen content failed to show.
                        // Make sure to set your reference to null so you don't
                        // show it a second time.
                        interstitialAd = null;
                        String errorMsg = adError.getMessage();
                        LLog.d(TAG, "onAdFailedToShowFullScreenContent." + adError.getMessage());
                        if (null != adCallback) {
                            adCallback.onAdClose(Constants.NODE_FAILED_TO_SHOW_EID, AD_TYPE, errorMsg, -1);
                            adCallback = null;
                        }
                        if (null != adStatusCallBack) {
                            adStatusCallBack.onAdDismiss(Constants.NODE_FAILED_TO_SHOW, AD_TYPE, errorMsg, -1, mAdUnitId, scenario);
                        }
                    }

                    @Override
                    public void onAdShowedFullScreenContent() {
                        // Called when fullscreen content is shown.
                        LLog.d(TAG, "onAdShowedFullScreenContent.");
                    }
                });
    }

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

    private long loadAdTime;

    private boolean wasLoadTimeLessThanNHoursAgo() {
        //广告会在一小时后过期
        long dateDifference = (new Date()).getTime() - loadAdTime;
        long numMilliSecondsPerHour = 3600000;
        boolean expired = dateDifference < numMilliSecondsPerHour;
        if (!expired) {
            StatsStaticHelper.onEvent("to", String.valueOf(false));
        }
        return expired;
    }

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

    public void showAd(Activity activity, String scenario) {
        LLog.d(TAG, "Will show ad.");
        setFullScreenContentCallback();
        this.scenario = scenario;
        interstitialAd.show(activity);
    }

    public void loadAd(Context context, int loadIndex) {
        if (context == null) {
            return;
        }
        LLog.d(TAG, "loadAd admob chaping start.");
        if (adIsLoading) {
            LLog.d(TAG, "loadAd admob isLoading. "+AdmobInterstitialManager.mAdUnitId);
            return;
        }

        if (isAdAvailable()) {
            LLog.d(TAG, "loadAd admob chaping 3.");
            return;
        }

        try {
            AdData adData = CpAdData.getInstance().getAdData(CP_ADMOB);
            if (adData == null) {
                LLog.w(TAG, " adData = null");
                return;
            }
            AdmobInterstitialManager.mAdUnitId = adData.getAdAdId(AdData.AD_TYPE_INTERSTITIAL, loadIndex);
            if (TextUtils.isEmpty(AdmobInterstitialManager.mAdUnitId)) {
                LLog.d(TAG, "loadAd admob chaping AdUnitId is empty  loadIndex = "+loadIndex);
                return;
            }
            if (isScreenLock(context)) {
                LLog.d(TAG, "loadAd admob chaping 1.");
                return;
            }
            if (!isScreenOn(context)) {
                LLog.d(TAG, "loadAd admob chaping 2.");
                return;
            }
            if (!GoogleMobileAdsConsentManager.getInstance(context).canRequestAds()) {
//                LLog.d(TAG, "loadAd admob chaping canRequestAds false.");
                try {
                    String country = CountryUtil.getLocalCountry(context);
                    StatsStaticHelper.onEvent("adC", country);
                } catch (Exception e) {

                }
//                return;
            }
            loadInterstitial(context, mAdUnitId);
        } catch (Exception e) {
            LLog.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();
    }
}
