package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import androidx.asynclayoutinflater.view.AsyncLayoutInflater
import androidx.recyclerview.widget.RecyclerView

open class AsyncCell @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    FrameLayout(context, attrs) {

    init {
        layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
    }

    // override with your layout Id
    open val layoutId = -1

    // delay first time bindView for better performance
    open val delayFirstTimeBindView = true

    // update layout parameter when inflated
    open val switchToWrapContentWhenInflated = false

    open var isInflated = false
    private var bindingFunction: (AsyncCell.() -> Unit)? = null

    open fun inflate() {
        AsyncLayoutInflater(context).inflate(layoutId, this) { view, _, _ ->
            isInflated = true
            addView(createDataBindingView(view))

            bindView()

            if (switchToWrapContentWhenInflated) {
                postDelayed({ switchToWrapContent() }, 50)
            }
        }
    }

    open fun bindView() {
        bindingFunction?.invoke(this)
        bindingFunction = null
    }

    fun bindWhenInflated(bindFunc: AsyncCell.() -> Unit) {
        if (isInflated) {
            bindFunc()
        } else {
            bindingFunction = bindFunc
        }
    }

    fun switchToWrapContent() {
        layoutParams = layoutParams.apply {
            width = WRAP_CONTENT
            height = WRAP_CONTENT
        }
    }

    open fun createDataBindingView(view: View): View? = view // override for usage with dataBinding

}