package com.adealink.weparty.room.micseat

import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.MainThread
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.hide
import com.adealink.weparty.commonui.ext.show
import java.lang.ref.WeakReference

abstract class AbsDynamicDecorView<V : View>(
    @IdRes val viewId: Int,
    private val dynamicLayers: DecorDynamicLayers,
) {
    private var viewRef: WeakReference<V> = WeakReference(null)

    fun view(action: (v: V) -> Unit) {
        getViewInner {
            action.invoke(it)
        }
    }

    /**
     * 获取已经添加的视图
     */
    fun view(): V? {
        return viewRef.get()
    }

    fun attach() {
        //调用view()填充
        view {}
    }

    @MainThread
    private fun getViewInner(action: (v: V) -> Unit) {
        val view = viewRef.get()
        if (view == null) {
            dynamicLayers.safeAddView<V>(viewId,
                onViewAdded = {
                    viewRef = WeakReference(it)
                    onViewAdded(it)
                }, addAfter = {
                    action.invoke(it)
                }
            )
        } else {
            action.invoke(view)
        }
    }

    /**
     * 用于控件初始化
     */
    open fun onViewAdded(view: V) {

    }

    @MainThread
    fun show() {
        getViewInner {
            it.show()
        }
    }

    @MainThread
    fun show(show: Boolean) {
        if (show) {
            show()
        } else {
            gone()
        }
    }

    @MainThread
    fun hide() {
        val view = viewRef.get() ?: return
        view.hide()
    }

    @MainThread
    fun gone() {
        val view = viewRef.get() ?: return
        view.gone()
    }

    fun isVisible(): Boolean {
        return viewRef.get()?.visibility == View.VISIBLE
    }

    fun isAttached(): Boolean {
        val view = viewRef.get()
        return view != null && view.isAttachedToWindow
    }
}