package com.ads.cal.notes.manager;

import android.app.Activity;
import android.content.Context;

import androidx.annotation.NonNull;

import com.ads.cal.notes.BaseApplication;
import com.ads.cal.notes.LLog;
import com.ads.cal.notes.callback.OnLoadAdEndCallBack;
import com.ads.cal.notes.callback.OnShowAdEndCallBack;
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.MobileAds;
import com.google.android.gms.ads.appopen.AppOpenAd;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

import java.util.Date;


public class WelcomeAdManager {
//
//    private static final String AD_UNIT_ID = "ca-app-pub-4184965935607567/5740399928";
    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921";

    private AppOpenAd appOpenAd = null;
    private boolean isLoading = false;
    private boolean isShowing = false;

    private OnLoadAdEndCallBack onLoadAdEndCallBack;
    private OnShowAdEndCallBack onShowAdEndCallBack;

    public boolean isShowing() {
        return isShowing;
    }

    /**
     * Keep track of the time an app open ad is loaded to ensure you don't show an expired ad.
     */
    private long loadTime = 0;

    /**
     * Constructor.
     */
    public WelcomeAdManager() {
    }

    private static final class AppOpenAdManagerHolder {
        static final WelcomeAdManager WELCOME_AD_MANAGER = new WelcomeAdManager();
    }

    public static WelcomeAdManager getInstance() {
        return AppOpenAdManagerHolder.WELCOME_AD_MANAGER;
    }

    public static void initAdMobile(Context context) {
        MobileAds.initialize(context, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) {
            }
        });
    }


    /**
     * Check if ad was loaded more than n hours ago.
     */
    private boolean wasLoadTimeLessThanNHoursAgo() {
        long dateDifference = (new Date()).getTime() - loadTime;
        long numMilliSecondsPerHour = 3600000;
        return (dateDifference < (numMilliSecondsPerHour * (long) 4));
    }

    /**
     * Check if ad exists and can be shown.
     */
    public boolean isAdAvailable() {
        // Ad references in the app open beta will time out after four hours, but this time limit
        // may change in future beta versions. For details, see:
        // https://support.google.com/admob/answer/9341964?hl=en
        return appOpenAd != null && wasLoadTimeLessThanNHoursAgo();
    }



    /**
     * Show the ad if one isn't already showing.
     *
     * @param activity                 the activity that shows the app open ad
     */
    public boolean showAdIfAvailable(
            @NonNull Activity activity) {
        // If the app open ad is already showing, do not show the ad again.
        if (isShowing) {
            LLog.d("The app open ad is already showing.");
            return false;
        }

        // If the app open ad is not available yet, invoke the callback then load the ad.
        if (!isAdAvailable()) {
            LLog.d("The app open ad is not ready yet.");
            loadAd();
            return false;
        }

        appOpenAd.setFullScreenContentCallback(
                new FullScreenContentCallback() {
                    /** Called when full screen content is dismissed. */
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        // Set the reference to null so isAdAvailable() returns false.
                        appOpenAd = null;
                        isShowing = false;

                        LLog.d("onAdDismissedFullScreenContent.");
                        if (null != onShowAdEndCallBack) {
                            onShowAdEndCallBack.onShowAdComplete();
                            onShowAdEndCallBack = null;
                        }
                        loadAd();
//                        FireBaseAnalyticsUtils.init().send(AD_OPEN_CLOSE);
                    }

                    /** Called when fullscreen content failed to show. */
                    @Override
                    public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                        appOpenAd = null;
                        isShowing = false;

                        LLog.d("onAdFailedToShowFullScreenContent: " + adError.getMessage());
                        if (null != onShowAdEndCallBack) {
                            onShowAdEndCallBack.onShowAdFailed(adError.getMessage());
                            onShowAdEndCallBack = null;
                        }
                        loadAd();
//                        FireBaseAnalyticsUtils.init().send(AD_OPEN_SHOW_FAILED);
                    }

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

                    @Override
                    public void onAdImpression() {
                        super.onAdImpression();
                        LLog.d("onAdImpression.");
//                        FireBaseAnalyticsUtils.init().send(AD_OPEN_EXP);
                    }

                    @Override
                    public void onAdClicked() {
                        super.onAdClicked();
//                        FireBaseAnalyticsUtils.init().send(AD_OPEN_CLK);
                    }
                });

        isShowing = true;
        appOpenAd.show(activity);
        return true;
    }


    public void setOnLoadAdCallBack(OnLoadAdEndCallBack onLoadAdEndCallBack) {
        this.onLoadAdEndCallBack = onLoadAdEndCallBack;
    }

    public void setOnShowAdCallBack(OnShowAdEndCallBack onShowAdEndCallBack) {
        this.onShowAdEndCallBack = onShowAdEndCallBack;
    }


    /**
     * Load an ad.
     *
     */
    public void loadAd() {
        // Do not load ad if there is an unused ad or one is already loading.
        if (isLoading || isAdAvailable()) {
            return;
        }

        isLoading = true;
        AdRequest request = new AdRequest.Builder().build();
        AppOpenAd.load(
                BaseApplication.getApplication(),
                AD_UNIT_ID,
                request,
                new AppOpenAd.AppOpenAdLoadCallback() {
                    /**
                     * Called when an app open ad has loaded.
                     *
                     * @param ad the loaded app open ad.
                     */
                    @Override
                    public void onAdLoaded(AppOpenAd ad) {
                        appOpenAd = ad;
                        isLoading = false;
                        loadTime = (new Date()).getTime();
                        if (onLoadAdEndCallBack != null) {
                            onLoadAdEndCallBack.onLoadAdComplete();
                            onLoadAdEndCallBack = null;
                        }

                        LLog.d("onAdLoaded.");
//                        FireBaseAnalyticsUtils.init().send(AD_OPEN_LOAD_SUCCESS);
                    }

                    /**
                     * Called when an app open ad has failed to load.
                     *
                     * @param loadAdError the error.
                     */
                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        isLoading = false;
                        if (onLoadAdEndCallBack != null) {
                            onLoadAdEndCallBack.onLoadAdFailed(loadAdError.getMessage());
                            onLoadAdEndCallBack = null;
                        }
                        LLog.d("onAdFailedToLoad: " + loadAdError.getMessage());
//                        FireBaseAnalyticsUtils.init().send(AD_OPEN_LOAD_FAILED);
                    }
                });
//        FireBaseAnalyticsUtils.init().send(AD_OPEN_START_LOAD);
    }

//    {
//        "Code": 0,
//            "Message": "Error while connecting to ad server: SSL handshake aborted: ssl=0x7f75486ac0: I\/O error during system call, Connection reset by peer",
//            "Domain": "com.google.android.gms.ads",
//            "Cause": "null",
//            "Response Info": {
//        "Response ID": "null",
//                "Mediation Adapter Class Name": "",
//                "Adapter Responses": [],
//        "Response Extras": {}
//    }
//    }

    {
//        "Code": 0,
//            "Message": "Received error HTTP response code: 403",
//            "Domain": "com.google.android.gms.ads",
//            "Cause": "null",
//            "Response Info": {
//        "Response ID": "null",
//                "Mediation Adapter Class Name": "",
//                "Adapter Responses": [],
//        "Response Extras": {}
//    }


//        {
//            "Code": 0,
//                "Message": "Error while connecting to ad server: SSL handshake aborted: ssl=0x7f6dc9f100: I\/O error during system call, Connection reset by peer",
//                "Domain": "com.google.android.gms.ads",
//                "Cause": "null",
//                "Response Info": {
//            "Response ID": "null",
//                    "Mediation Adapter Class Name": "",
//                    "Adapter Responses": [],
//            "Response Extras": {}
//        }
//        }
    }

}
