package com.convenient.android.lib.ui.sample.ad.activity

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.composition.android.lib.ad.AdLoad
import com.composition.android.lib.ad.AdManager
import com.composition.android.lib.ad.basic.AdResult
import com.composition.android.lib.ad.util.adLogE
import com.convenient.android.common.base.viewbinding.BaseBindingActivity
import com.convenient.android.common.extension.setViewsClick
import com.convenient.android.common.utils.ToastUtil
import com.convenient.android.lib.R
import com.convenient.android.lib.databinding.ActivityAdInterstitialBinding
import com.convenient.android.lib.ui.sample.ad.model.Datas
import kotlinx.coroutines.launch

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/8
 * description:
 */
class AdFullScreenAdActivity : BaseBindingActivity<ActivityAdInterstitialBinding>(ActivityAdInterstitialBinding::inflate) {

    private var adResult : AdResult.Success? = null

    private var adSlotName : String = Datas.INTERSTITIAL

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        adSlotName = intent.getStringExtra("ad_slot_name")?:Datas.INTERSTITIAL
        binding.tvAdSlotName.text = "当前加载广告位为:${adSlotName}"

        setViewsClick({
            when (it.id) {
                R.id.btn_load_full_screen_ad -> {
                    loadFullScreenAd {
                        adResult = it
                    }
                }
                R.id.btn_show_full_screen_ad->{
                    showRewardVideo()
                }
                R.id.btn_load_and_show->{
                    loadFullScreenAd {
                        adResult = it
                        showRewardVideo()
                    }
                }
                else -> {}
            }
        }, binding.btnLoadFullScreenAd, binding.btnShowFullScreenAd, binding.btnLoadAndShow)

    }


    private fun loadFullScreenAd(result : (AdResult.Success) -> Unit){
        lifecycleScope.launch {
            AdLoad.loadAd(this@AdFullScreenAdActivity, adSlotName)
                .collect{
                    if (it is AdResult.Success){
                        result.invoke(it)
                        ToastUtil.showLongToast(this@AdFullScreenAdActivity, "${adSlotName}广告加载成功")
                    }else{
                        adLogE(msg = it.msg, tag = AdManager.TAG)
                    }
                }
        }
    }

    private fun showRewardVideo(){
        adResult?.let {
            AdLoad.showFullScreenAd(this, it){
                onAdClose {
                    adResult?.adObject = null
                    adResult = null
                }
                onAdRewarded {
                    adLogE(AdManager.TAG, "获取到奖励")
                }
            }
        }
    }
}