package com.composition.android.lib.ad.basic

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.findViewTreeLifecycleOwner
import com.composition.android.lib.ad.AdManager
import com.composition.android.lib.ad.util.adLog
import com.composition.android.lib.ad.util.parentRemove

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/6
 * description:
 */
abstract class BasicAdView<T : View> : LinearLayout, DefaultLifecycleObserver {

    var adResult: AdResult.Success? = null

    var adView: T? = null

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

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)

    init {
        gravity = Gravity.CENTER
    }

    /**
     * 对广告布局进行渲染
     */
    fun render(adResult: AdResult.Success) {
        this.adResult = adResult
        adView = adContentView()
        adView?.let {
            it.parentRemove()
            removeAllViews()
            addView(it)
        }
    }


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        adLog(AdManager.TAG, javaClass.simpleName + " 绑定到Window")
        findViewTreeLifecycleOwner()?.lifecycle?.addObserver(this)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        adLog(AdManager.TAG, javaClass.simpleName + " 从Window移除")
        onDestroy()
        findViewTreeLifecycleOwner()?.lifecycle?.removeObserver(this)
    }


    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        adLog(AdManager.TAG, javaClass.simpleName + " onResume")
        onResume()
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        adLog(AdManager.TAG, javaClass.simpleName + " onPause")
        onPause()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        adLog(AdManager.TAG, javaClass.simpleName + " onDestroy")
        owner.lifecycle.removeObserver(this)
        findViewTreeLifecycleOwner()?.lifecycle?.removeObserver(this)
        onDestroy()

    }

    abstract fun adContentView(): T?

    abstract fun onResume()

    abstract fun onPause()

    abstract fun onDestroy()

}