package com.develop.common.widget

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.updateText
import com.develop.common.R
import com.develop.common.data_repo.db.CommonSearchItem
import com.develop.common.data_repo.db.CommonSearchModel
import com.develop.common.databinding.CommonSearchViewBinding
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.google.android.flexbox.*


class CommonSearchLayout : LinearLayout {

    private var binding: CommonSearchViewBinding

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


    private var dataList = mutableListOf<CommonSearchItem>()

    var onHotWordsSelectedListener: OnHotWordsSelectedListener? = null

    init {
        val root = View.inflate(context, R.layout.common_search_view, this)
        binding = CommonSearchViewBinding.bind(root)
        val flexboxLayoutManager = FlexboxLayoutManager(context)
        flexboxLayoutManager.flexWrap = FlexWrap.WRAP
        flexboxLayoutManager.flexDirection = FlexDirection.ROW
        flexboxLayoutManager.alignItems = AlignItems.STRETCH
        flexboxLayoutManager.justifyContent = JustifyContent.FLEX_START
        binding.searchRecycler.apply {
            layoutManager = flexboxLayoutManager
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.bottom = dp24
                }
            })
            setup {
                addType<CommonSearchItem>(R.layout.item_search_title_view)
                onBind {
                    findView<AppCompatTextView>(R.id.tv_search_name)
                        .updateText(getModel<CommonSearchItem>().name)
                }
                R.id.tv_search_name.onClick {
                    onHotWordsSelectedListener?.onHotWordsSelected(dataList[absoluteAdapterPosition].name)
                }
            }
        }.models = dataList

    }

    fun updateData(model: CommonSearchModel) {
        dataList.clear()
        dataList.addAll(model.data)
        binding.searchRecycler.models = dataList
    }

    interface OnHotWordsSelectedListener {
        fun onHotWordsSelected(hotWord: String)
    }

    companion object {
        var dp24 = (com.develop.base.R.dimen.convert_24px).resId2Dimension().toInt()
    }
}