package com.pan_american.android.data.model.resource_management.market_customer.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.data.model.resource_management.market_customer.entity.MarketCustomer
import com.pan_american.android.data.model.resource_management.market_customer.entity.MarketCustomerListItem

class MarketCustomerListAdapter(var list: ArrayList<MarketCustomerListItem>): RecyclerView.Adapter<MarketCustomerListAdapter.ViewHolder>() {

    var isEnableMultiselectMode = false

    lateinit var onRecyclerViewItemClick: OnRecyclerViewItemClick<MarketCustomer>

    inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val itemCheckView: LinearLayout = view.findViewById(R.id.item_check_view)
        val itemCheck: CheckBox = view.findViewById(R.id.item_check)
        val unitName: TextView = view.findViewById(R.id.unit_name)
        val city: TextView = view.findViewById(R.id.city)
        val customerName: TextView = view.findViewById(R.id.customer_name)
        val customerJob: TextView = view.findViewById(R.id.customer_job)
        val phoneNumber: TextView = view.findViewById(R.id.phone_number)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(OASystem.context).inflate(R.layout.item_market_customer_list, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount() = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = list[position]

        holder.unitName.text = item.client
        holder.city.text = item.location
        holder.customerName.text = item.contact
        holder.customerJob.text = item.job
        holder.phoneNumber.text = item.telephone

        if (isEnableMultiselectMode) {
            holder.itemCheckView.visibility = View.VISIBLE
            holder.itemCheck.isChecked = item.isChecked
            holder.itemCheck.isClickable = false
        } else {
            holder.itemCheckView.visibility = View.GONE
        }

        holder.itemCheck.setOnCheckedChangeListener { _, isChecked ->
            list[holder.absoluteAdapterPosition].isChecked = isChecked
        }

        holder.itemView.setOnClickListener {
            onRecyclerViewItemClick.onItemClick(position)
            if (isEnableMultiselectMode) {
                holder.itemCheck.isChecked = item.isChecked
            }
        }
    }

    interface OnRecyclerViewItemClick<T> {
        fun onItemClick(position: Int)
    }
}