package com.rdiot.yx485.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.viewpager.widget.PagerAdapter
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.divider
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.R
import com.rdiot.yx485.bean.DeviceTypeData
import com.rdiot.yx485.databinding.ItemDeviceTypeBinding
import com.rdiot.yx485.databinding.ItemDeviceTypeVpBinding

/**
 * 选择设备类型adapter
 */
class SelectDeviceTypeAdapter(
    private val context: Context?, private val list: ArrayList<DeviceTypeData>,
    private val onItemClickListener: OnItemClickListener
) : PagerAdapter() {

    override fun getCount(): Int {
        return list.size;
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view == `object`
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val binding = DataBindingUtil.inflate<ItemDeviceTypeVpBinding>(
            LayoutInflater.from(context),
            R.layout.item_device_type_vp,
            null,
            false
        )
        binding.itemDeviceTypeVpRv.grid(1).divider {
            setDrawable(R.drawable.divider_horizontal)
            orientation = DividerOrientation.GRID
            includeVisible = true
        }.setup {
            addType<DeviceTypeData>(R.layout.item_device_type)
            onBind {
                getBinding<ItemDeviceTypeBinding>().context = context // ViewBinding/DataBinding都支持
            }
            R.id.item_device_type.onClick {
                if (list.size > position) {
                    val i = list[position].children?.get(this.modelPosition)
                    onItemClickListener.onClick(this.modelPosition, i)
                }
            }
        }
        if (list.size > position)
            binding.itemDeviceTypeVpRv.models = list[position].children
        container.addView(binding.itemDeviceTypeVpRv)
        return binding.itemDeviceTypeVpRv
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//        super.destroyItem(container, position, `object`)
        container.removeViewAt(position)
    }

    interface OnItemClickListener {
        fun onClick(position: Int, deviceTypeData: DeviceTypeData?)
    }
}