package com.zxhy.fastfilemanagerpro.kokoads

import android.app.Activity
import android.content.Context
import android.util.Log
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.zxhy.fastfilemanagerpro.MyApplication
import java.util.Date

class KokoOpenAdManager {

    private var googleMobileAdsConsentManager: GoogleMobileAdsConsentManager =
        GoogleMobileAdsConsentManager.getInstance(MyApplication.ApplicationContext)

    var isInit = false
    private var appOpenAd: AppOpenAd? = null
    private var isLoadingAd = false
    private var isShowingAd = false
    private var loadTime: Long = 0//广告加载的时间

    var adShowing: (() -> Unit)? = null
    var adShowComplete: ((showed: Boolean) -> Unit)? = null
    var adLoadComplete: ((loaded: Boolean) -> Unit)? = null


    fun clearAllCallBack() {
        adShowing = null
        adShowComplete = null
        adLoadComplete = null
    }

    /**
     * 广告加载回调
     */
    private inner class AppOpenAdLoadCallback : AppOpenAd.AppOpenAdLoadCallback() {
        override fun onAdLoaded(ad: AppOpenAd) {
            appOpenAd = ad
            isLoadingAd = false
            loadTime = Date().time
            adLoadComplete?.invoke(true)
        }

        override fun onAdFailedToLoad(loadAdError: LoadAdError) {
            isLoadingAd = false
            adLoadComplete?.invoke(true)
        }
    }

    /**
     * 广告全屏回调
     */
    inner class MyFullScreenContentCallback(val activity: Activity) : FullScreenContentCallback() {
        override fun onAdShowedFullScreenContent() {
            adShowing?.invoke()
            Log.d(LOG_TAG, "onAdShowedFullScreenContent.")
        }

        override fun onAdDismissedFullScreenContent() {
            Log.d(LOG_TAG, "onAdDismissedFullScreenContent.")
            appOpenAd = null
            isShowingAd = false
            adShowComplete?.invoke(true)
            //加载新广告
            if (googleMobileAdsConsentManager.canRequestAds) {
                loadAd(activity)
            }
        }


        override fun onAdFailedToShowFullScreenContent(adError: AdError) {
            Log.d(LOG_TAG, "onAdDismissedFullScreenContent.")
            appOpenAd = null
            isShowingAd = false
            adShowComplete?.invoke(false)
            //加载新广告
            if (googleMobileAdsConsentManager.canRequestAds) {
                loadAd(activity)
            }
        }
    }


    /**
     * 加载广告
     */
    fun loadAd(context: Context) {
        if (isLoadingAd || existOpenAdCanShow()) {
            return
        }
        isLoadingAd = true

        val request = AdRequest.Builder().build()
        AppOpenAd.load(
            context,
            AD_UNIT_ID,
            request, AppOpenAdLoadCallback()
        )
    }

    /**
     * 显示广告
     */
    fun showAdIfAvailable(activity: Activity) {
        val TAG = "showAdIfAvailable"
        if (isShowingAd) {
            Log.e(TAG, "isShowingAd=${isShowingAd}")
            return
        }

        if (!existOpenAdCanShow()) {
            Log.e(TAG, "existOpenAdCanShow=false")
            adShowComplete?.invoke(false)
            if (googleMobileAdsConsentManager.canRequestAds) {
                loadAd(activity)
            }
            return
        }

        appOpenAd?.fullScreenContentCallback = MyFullScreenContentCallback(activity)

        isShowingAd = true
        Log.e(TAG, "调用展示广告")
        appOpenAd?.show(activity)
    }

    /**
     * 检查已有广告是否可显示
     */
    fun existOpenAdCanShow(): Boolean {
        return appOpenAd != null && adLoadLessInterval(1)
    }

    /**
     * ad加载小于时间间隔
     */
    private fun adLoadLessInterval(hours: Int): Boolean {
        val dateDifference: Long = Date().time - loadTime
        val mSecondsPerHour: Long = 3600000
        return dateDifference < mSecondsPerHour * hours
    }

    companion object {
        private const val LOG_TAG = "KokoOpenAdManager"
        private const val AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921"
    }
}