package com.sybotan.android.demo.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.RadioButton
import com.sybotan.android.demo.R
import com.sybotan.android.demo.entitiies.DeviceType

class DeviceTypeAdapter(
    val types: List<DeviceType>,
    val context: Context,
    val block: (type: DeviceType) -> Unit
) : BaseAdapter() {

    private var checkType: DeviceType? = null
    private val holders = mutableListOf<Holder>()
    override fun getCount(): Int {
        return types.size
    }

    override fun getItem(position: Int): DeviceType {
        return types[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var view = convertView
        val holder: Holder
        if (view == null) {
            holder = Holder()
            view = LayoutInflater.from(context).inflate(R.layout.item_device, parent, false)
            holder.deviceCb = view.findViewById(R.id.deviceCb)

            view.tag = holder
        } else {
            holder = view.tag as Holder
        }
        holders.add(holder)
        val type = types[position]
        holder.deviceCb.text = type.name
        holder.deviceCb.setOnClickListener {
            holders.forEach { h ->
                h.deviceCb.isSelected = false
                h.deviceCb.isChecked = false
            }
            val cb = it as CheckBox
            if (!cb.isSelected) {
                cb.isSelected = true
                cb.isChecked = true
                checkType = type
              //  checkTypes.add(type)

            } else {
                cb.isSelected = false
                cb.isChecked = false
                checkType = type
             //   checkTypes.remove(type)
            }

            block(checkType!!)
        }
        return view!!
    }

    inner class Holder {
        lateinit var deviceCb: CheckBox
    }

}