/*
 *    Copyright 2018-2019 adview.com, Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.adview.mobile.adviewkotlindemo.activities.ads.admob

import android.os.Bundle
import android.util.Log
import android.view.View
import com.google.android.gms.ads.AdRequest
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.adview.sdk.admob.AdMobMediationInterstitialUtils
import com.adview.sdk.admob.AdviewInterstitialAdapter
import com.adview.sdk.api.data.AdUnitFormat
import com.adview.sdk.api.mediation.MediationInterstitialAdUnit
import com.adview.mobile.adviewkotlindemo.activities.BaseAdActivity
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.FullScreenContentCallback
import java.util.*

class AdMobDisplayInterstitialActivity : BaseAdActivity() {

    companion object {
        const val AD_UNIT_ID = "ca-app-pub-7283949697136772/5248357557" //admob instl
        const val CONFIG_ID = "POSIDfg0muzt20z0y" //official line
    }

    private var adUnit: MediationInterstitialAdUnit? = null
    private var interstitialAd: InterstitialAd? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        createAd()
    }

    private fun createAd() {
        // button load
        binding.btnLoadAd.visibility = View.VISIBLE
        binding.btnLoadAd.isEnabled = false
        binding.btnShowAd.visibility = View.GONE

        val extras = Bundle()
        val mediationUtils = AdMobMediationInterstitialUtils(extras)

        adUnit = MediationInterstitialAdUnit(
            this,
            CONFIG_ID,
            EnumSet.of(AdUnitFormat.BANNER,AdUnitFormat.VIDEO),
            mediationUtils
        )


        Log.d("AdMobInterstitial", "Starting fetchDemand immediately...")
        adUnit?.fetchDemand { result ->
            Log.d("AdMobInterstitial", "Fetch demand result: $result")
            
            // 2. fetchDemand success
            binding.btnLoadAd.isEnabled = true
            
            // 3. button load
            binding.btnLoadAd.setOnClickListener {
                Log.d("AdMobInterstitial", "Button clicked! Loading AdMob with potential expired demand...")
                binding.btnLoadAd.isEnabled = false

                val request = AdRequest.Builder()
                    .addNetworkExtrasBundle(AdviewInterstitialAdapter::class.java, extras)
                    .build()

                InterstitialAd.load(
                    this,
                    AD_UNIT_ID,
                    request,
                    object : InterstitialAdLoadCallback() {
                        override fun onAdLoaded(interstitial: InterstitialAd) {
                            Log.d("AdMobInterstitial", "==== on InterstitialAd loaded ====")
                            interstitialAd = interstitial
                            interstitialAd?.fullScreenContentCallback = createFullScreenContentCallback()

                            binding.btnShowAd.visibility = View.VISIBLE
                            binding.btnShowAd.setOnClickListener {
                                interstitialAd?.show(this@AdMobDisplayInterstitialActivity)
                                binding.btnShowAd.visibility = View.GONE
                            }
                        }

                        override fun onAdFailedToLoad(error: LoadAdError) {
                            Log.d("AdMobInterstitial", "=== Failed to load ad: $error ===")
                            interstitialAd = null
                            binding.btnLoadAd.isEnabled = true
                        }
                    })
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        adUnit?.destroy()
    }

    protected fun createFullScreenContentCallback(): FullScreenContentCallback {
        return object : FullScreenContentCallback() {
            override fun onAdClicked() {
                Log.d("AdMobInterstitial", "==== onAdClicked ===")
            }
            override fun onAdImpression() {
                Log.d("AdMobInterstitial", "==== onAdImpression ===")
            }
            override fun onAdShowedFullScreenContent() {
                Log.d("AdMobInterstitial", "==== onAdShowedFullScreenContent ===")
            }
            override fun onAdDismissedFullScreenContent() {
                Log.d("AdMobInterstitial", "==== onAdDismissedFullScreenContent ===")
                // after close can create ad again
                createAd()
            }
            override fun onAdFailedToShowFullScreenContent(p0: AdError) {
                Log.d("AdMobInterstitial", "==== onAdFailedToShowFullScreenContent ===")
                binding.btnLoadAd.isEnabled = true
            }
        }
    }
}
