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 com.sybotan.android.demo.R
import com.sybotan.android.demo.entitiies.RelationEq

class ServerRelAdapter(
    val eqs: List<RelationEq>,
    val context: Context,
    val block: (eq: List<RelationEq>) -> Unit
) : BaseAdapter() {
    private val holders = mutableListOf<Holder>()

    private val mResults = mutableListOf<RelationEq>()

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

    override fun getItem(position: Int): RelationEq {
        return eqs[position]
    }

    override fun getItemId(position: Int): Long {
        return eqs[position].deviceId.hashCode().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_relation, parent, false)
            holder.relationCb = view.findViewById(R.id.relationCb)

            view.tag = holder
        } else {
            holder = view.tag as Holder
        }
        // holders.add(holder)
        val eq = eqs[position]
        holder.relationCb.text = eq.type
        holder.relationCb.setOnClickListener {
            holders.forEach { h ->
                h.relationCb.isSelected = false
                h.relationCb.isChecked = false
            }
            val cb = it as CheckBox
            if (!cb.isSelected) {
                cb.isSelected = true
                cb.isChecked = true
                mResults.add(eq)
            } else {
                cb.isSelected = false
                cb.isChecked = false
                mResults.remove(eq)
            }

            block(mResults)
        }
        return view!!
    }

    inner class Holder {
        lateinit var relationCb: CheckBox
    }
}