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 android.util.Log;

import androidx.annotation.NonNull;

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.appopen.AppOpenAd;
import com.or.ange.dot.utils.LLog;

import java.util.Date;

public class AdmobOpenManager {

    private static final String TAG = "AdmobOpenManager";
    private static final String AD_TYPE = "kaipin";


    private static final class AdManagerHolder {
        static final AdmobOpenManager adManager = new AdmobOpenManager();
    }
    public static AdmobOpenManager instance() {
        return AdManagerHolder.adManager;
    }
    private AdCallback adCallback;
    private AppOpenAd appOpenAd;
    private boolean isLoadingAd = false;
    private boolean isShowingAd = false;
    private long requestTime;

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

    private void loadOpen(Context context, String adUnitId) {
        if (isLoadingAd || isAdAvailable()) {
            LLog.d(TAG, "loadAd admob open 3.");
            return;
        }
        LLog.d(TAG, "loadAd admob open end.");
        AdRequest adRequest = new AdRequest.Builder().build();
        requestTime = System.currentTimeMillis();
        isLoadingAd = true;
        AppOpenAd.load(context, adUnitId, adRequest, new AppOpenAd.AppOpenAdLoadCallback() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                LLog.i(TAG, loadAdError.getMessage());
                isLoadingAd = false;
                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);
                requestTime = System.currentTimeMillis() - requestTime;
                if (null != adCallback) {
                    adCallback.onAdError(Constants.NODE_ERROR_EID, AD_TYPE, error, requestTime);
                }
            }

            @Override
            public void onAdLoaded(@NonNull AppOpenAd ad) {
                LLog.i(TAG, "onAdLoaded");
                AdmobOpenManager.this.appOpenAd = ad;;
                isLoadingAd = false;
                loadAdTime = (new Date()).getTime();
                requestTime = System.currentTimeMillis() - requestTime;
                if (null != adCallback) {
                    adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, AD_TYPE, "loaded", requestTime);
                }
            }

        });
    }

    private void setFullScreenContentCallback() {
        if (appOpenAd == null) {
            return;
        }
        appOpenAd.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);
                        }
                    }

                    @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);
                        }
                        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.
                        appOpenAd = null;
                        isShowingAd = false;
                        LLog.d(TAG, "onAdDismissedFullScreenContent.");
                        if (null != adCallback) {
                            adCallback.onAdClose(Constants.NODE_CLOSE_EID, AD_TYPE, "", -1);
                            adCallback = null;
                        }
                    }

                    @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.
                        appOpenAd = null;
                        isShowingAd = false;
                        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;
                        }
                    }

                    @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 appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
    }

    private long loadAdTime;

    private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
        //广告会在4小时后过期
        long dateDifference = (new Date()).getTime() - loadAdTime;
        long numMilliSecondsPerHour = 3600000;
        return (dateDifference < (numMilliSecondsPerHour * numHours));
    }

    //ca-app-pub-3940256099942544/9257395921
    private static String mAdUnitId;

    public void showAd(Activity activity) {
        if (isShowingAd) {
            Log.d(TAG, "The app open ad is already showing.");
            return;
        }
        LLog.d(TAG, "Will show ad.");
        setFullScreenContentCallback();
        isShowingAd = true;
        appOpenAd.show(activity);
    }

    public void loadAd(Context context) {
        LLog.d(TAG, "loadAd admob open start.");
        try {
            AdData adData = CpAdData.getInstance().getAdData(CP_ADMOB);
            if (adData == null) {
                LLog.w(TAG, " adData = null");
                return;
            }
            AdmobOpenManager.mAdUnitId = adData.getAdAdId(AdData.AD_TYPE_OPEN, 0);
            if (TextUtils.isEmpty(AdmobOpenManager.mAdUnitId)) {
                LLog.d(TAG, "loadAd admob open 0.");

                return;
            }
            if (isScreenLock(context)) {
                LLog.d(TAG, "loadAd admob open 1.");

                return;
            }
            if (!isScreenOn(context)) {
                LLog.d(TAG, "loadAd admob open 2.");
                return;
            }
            if (!GoogleMobileAdsConsentManager.getInstance(context).canRequestAds()) {
                LLog.d(TAG, "loadAd admob open canRequestAds false.");
                return;
            }
            loadOpen(context, mAdUnitId);
        } catch (Exception e) {
            LLog.d(TAG, "loadAd open. e ----" + e.getMessage());
        }
    }

    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();
    }
}
