package com.composition.android.lib.ad.widget

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.composition.android.lib.ad.AdLoad
import com.composition.android.lib.ad.R
import com.composition.android.lib.ad.basic.AdResult
import com.composition.android.lib.ad.basic.buildBannerAdViewHolder
import com.composition.android.lib.ad.impl.NormalAdListener
import com.composition.android.lib.ad.util.getActivityFromView
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/7
 * description: 横幅广告View
 * 可以直接写入在布局中，设置ad_slot_name（广告位名称）后，自动进行加载展示横幅广告
 * 广告跟随生命周期自动销毁
 */
class BannerAdView : LinearLayout{

    /**
     * 广告位名称
     */
    private var adSlotName : String = ""

    private var adResult : AdResult? = null

    init {
        orientation = VERTICAL
    }

    constructor(context: Context?) : super(context)

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs){
        init(attrs)
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private fun init(attrs: AttributeSet?){
        val typedArray: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.BannerAdView)
        //获取到配置的广告名称
        adSlotName = typedArray.getString(R.styleable.BannerAdView_ad_slot_name)?:""
        typedArray.recycle()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        loadAd()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        destroyAd()
    }


    private fun loadAd(){
        findViewTreeLifecycleOwner()?.lifecycleScope?.launch {
            destroyAd()
            adResult = AdLoad.loadAd(context, adSlotName)
                .firstOrNull()
            if (adResult is AdResult.Success){
                AdLoad.getBannerAdView(context, adResult as AdResult.Success, buildBannerAdViewHolder {
                    this.activity = getActivityFromView()
                    this.adListener = object : NormalAdListener(){
                        override fun onAdDisLike() {
                            super.onAdDisLike()
                            isVisible = false
                            removeAllViews()
                            destroyAd()
                        }
                    }
                })?.let {
                    removeAllViews()
                    addView(it)
                    isVisible = true
                }
            }
        }
    }

    private fun destroyAd(){
        AdLoad.destroyAd(adResult)
    }

    /**
     * 更新广告
     */
    fun setAdSlotName(adSlotName : String){
        this.adSlotName = adSlotName
        loadAd()
    }

    /**
     * 移除广告
     */
    fun removeAd(){
        removeAllViews()
        isVisible = false
    }


}