package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.content.Context
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.DialogServersCalendearDetailReportItemBinding
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class ServersCalendarDetailReportAdapter(
    context: Context,
    private val serverList: List<ServerCalendarEntity>
) : BaseRecyclerAdapter<ServersCalendarDetailReportAdapter.ServersCalendarDetailReportViewHolder>(context) {

    private val selectedPositions = mutableListOf<Int>()

    val selectedServerCalendarList: List<ServerCalendarEntity> get() = serverList.filterIndexed { index, _ ->
        selectedPositions.contains(index)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ServersCalendarDetailReportViewHolder {
        val view = mLayoutInflater.inflate(R.layout.dialog_servers_calendear_detail_report_item, parent, false)
        return ServersCalendarDetailReportViewHolder(DialogServersCalendearDetailReportItemBinding.bind(view))
    }

    override fun getItemCount(): Int = serverList.size

    override fun onBindViewHolder(holder: ServersCalendarDetailReportViewHolder, position: Int) {
        val serverCalendarEntity = serverList[position]

        holder.bindItem(serverCalendarEntity)

        holder.binding.cb.isChecked = selectedPositions.contains(position)

        val layoutParams = holder.binding.root.layoutParams as MarginLayoutParams

        holder.binding.root.layoutParams = layoutParams.apply {
            bottomMargin = if (position == serverList.size - 1) 16F.dip2px() else 0
        }

        holder.binding.root.setOnClickListener {
            if (selectedPositions.contains(position)) {
                selectedPositions.remove(position)
            } else {
                selectedPositions.add(position)
            }
            notifyItemChanged(position)
        }
    }

    class ServersCalendarDetailReportViewHolder(val binding: DialogServersCalendearDetailReportItemBinding) :
        BaseRecyclerViewHolder<Any>(binding.root) {

        fun bindItem(data: ServerCalendarEntity) {
            binding.name.text = data.getNote()
            binding.time.text = data.getFormatTime("HH:mm")
            binding.remark.text = data.remark

            binding.name.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(binding.root.context))
            binding.time.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(binding.root.context))
            binding.remark.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(binding.root.context))
        }
    }
}