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.SpacePipe

class SpacePipeAdapter(
    val pipes: List<SpacePipe>,
    val context: Context,
    val block: (eq: SpacePipe?) -> Unit
) : BaseAdapter() {
    private val holders = mutableListOf<Holder>()
    private var result: SpacePipe? = null
    override fun getCount(): Int {
        return pipes.size
    }

    override fun getItem(position: Int): SpacePipe {
        return pipes[position]
    }

    override fun getItemId(position: Int): Long {
        return pipes[position].pipeId.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 = pipes[position]
        holder.relationCb.text = "${eq.name}-${eq.remark}"
        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
                result = eq
            } else {
                cb.isSelected = false
                cb.isChecked = false
                result = null
            }

            block(result)
        }
        return view!!
    }

    inner class Holder {
        lateinit var relationCb: CheckBox
    }
}