package com.rdiot.yx485.adapter

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rdiot.yx485.adapter.DeviceTypeContentAdapter.DeviceTypeListView
import com.rdiot.yx485.bean.DeviceTreeBean
import com.rdiot.yx485.bean.DeviceTreeBean.DataBean.ChildrenBean
import com.rdiot.yx485.databinding.ItemDeviceTypeContentBinding
import com.rdiot.yx485.device.view.ResetActivity

class DeviceTypeContentAdapter(val list: List<DeviceTreeBean.DataBean>?, context: Context) :
    RecyclerView.Adapter<DeviceTypeListView>() {

    private var mContext = context
    private var mList: List<DeviceTreeBean.DataBean>? = list

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): DeviceTypeListView {
        val binding =
            ItemDeviceTypeContentBinding.inflate(LayoutInflater.from(mContext), parent, false)
        return DeviceTypeListView(binding)
    }

    override fun onBindViewHolder(
        holder: DeviceTypeListView,
        position: Int
    ) {
        holder.setIsRecyclable(false)
        holder.bindView(position)
    }

    override fun getItemCount(): Int {
        return mList?.size ?: 0
    }

    inner class DeviceTypeListView(val binding: ItemDeviceTypeContentBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bindView(position: Int) {
            val device = mList?.get(position)
            device?.let {
                if (!TextUtils.isEmpty(it.name)) {
                    binding.tvSubtitle.text = it.name
                }

                val adapter = DeviceTypeListAdapter(
                    it.children,
                    object : DeviceTypeListAdapter.OnItemClickListener {
                        override fun onItemClick(item: ChildrenBean?) {
                            item?.let {
                                gotoDeviceBind(it)
                            }
                        }
                    })
                binding.rvDeviceTypeList.layoutManager = GridLayoutManager(mContext, 3)
                binding.rvDeviceTypeList.adapter = adapter
            }

        }
    }


    private fun gotoDeviceBind(item: ChildrenBean) {
        val bundle = Bundle()
        bundle.putBoolean("isMaster", item.is_master)
        bundle.putBoolean("bluetooth", item.bluetooth)
        bundle.putBoolean("need_device_code", item.need_device_code)
        bundle.putString("device_type_id", item.record_id)
        bundle.putString("blue_code", item.blue_code)
        bundle.putString("device_name", item.name)
        ResetActivity.newIntent(mContext, bundle, item.steps)
    }
}