package com.doverfuelingsolutions.issp.view.adapter

import android.view.View
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.doverfuelingsolutions.issp.DFSApplication
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.fusion.FusionManager
import kotlinx.android.synthetic.main.adapter_choose_item.view.*

class ChooseListAdapter(private val chooseList: List<String>, private val handler: (item: String) -> Unit,
                        private val chooseEffect: Boolean = false,
                        private var signOrderList: HashMap<String,Boolean> = hashMapOf()) :
    RecyclerView.Adapter<ChooseListAdapter.ChooseViewHolder>() {

    private var selectedIndex = 0

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChooseViewHolder {
        val view = View.inflate(parent.context, R.layout.adapter_choose_item, null)
        return ChooseViewHolder(view)
    }


    override fun onBindViewHolder(holder: ChooseViewHolder, position: Int) {
        holder.itemView.chooseItemView.text = chooseList[position]

        //油品页面选择了某一油品，那一项变深色，但是油品选择页面可能会删除，只剩下油枪选择页面
        if (chooseEffect) {
            val color = if (!chooseEffect || selectedIndex == position)
                ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimary, null)
            else
                ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimaryTransparent, null)
            holder.itemView.chooseItemView.setBackgroundColor(color)
        }

        //油枪选择页面中，有订单的油枪深色显示
        val pumpId = FusionManager.nozzles.find { it.physicalId.toString() == chooseList[position] }?.pumpId
        val color: Boolean = signOrderList[pumpId.toString()] == true
        if (color) {
            holder.itemView.chooseItemView.setBackgroundColor(
                ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimary, null)
            )
        } else {
            holder.itemView.chooseItemView.setBackgroundColor(
                ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimaryTransparent, null)
            )
        }



        holder.itemView.chooseItemView.setOnClickListener {
            if (chooseEffect) {
                selectedIndex = position
                notifyDataSetChanged()
            }
            handler.invoke(chooseList[position])
        }
    }

    override fun getItemCount(): Int = chooseList.size

    fun setSignColor(map: HashMap<String,Boolean>){
        this.signOrderList.clear()
        this.signOrderList = map
        notifyDataSetChanged()
    }

    class ChooseViewHolder(view: View) : RecyclerView.ViewHolder(view)
}