package com.gh.common.pop

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.appcompat.app.AppCompatActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.databinding.PopReserveAllSelectBinding
import com.gh.gamecenter.mygame.MyReservationFragment

class ReserveAllSelectPop(
    val binding: PopReserveAllSelectBinding,
    private val listener: OnReserveAllSelectListener
) : BugFixedPopupWindow(binding.root, ViewGroup.LayoutParams.MATCH_PARENT, 56F.dip2px()) {

    private var pageStatus: MyReservationFragment.ReservePageState =
        MyReservationFragment.ReservePageState.EnableAutoDownload

    private val onCheckedChangeListener = { _: CompoundButton, isChecked: Boolean ->
        val count = listener.selectAll(isChecked)
        updateSelectedCount(count)
    }

    init {
        isOutsideTouchable = false
        binding.cbAll.setOnCheckedChangeListener(onCheckedChangeListener)
        binding.tvSubmit.setOnClickListener {
            listener.submit()
        }
    }

    fun show(state: MyReservationFragment.ReservePageState, context: Context) {
        enableSubmit(false)
        binding.tvSubmit.setText(
            if (state == MyReservationFragment.ReservePageState.EnableAutoDownload) {
                R.string.enable_automatic_downloading_with_wifi
            } else {
                R.string.cancel_reserve
            }
        )

        // 清空上一次的状态
        pageStatus = state
        updateSelectedCount(0)

        if (!isShowing) {
            showAtLocation((context as AppCompatActivity).window.decorView, Gravity.BOTTOM, 0, 0)
        }

    }

    fun updateSelectedCount(count: Int) {
        if (count == 0) {
            enableSubmit(false)

            binding.cbAll.setOnCheckedChangeListener(null)
            binding.cbAll.isChecked = false
            binding.cbAll.setOnCheckedChangeListener(onCheckedChangeListener)
        } else {
            enableSubmit(true)
            binding.tvNumber.text = binding.root.context.getString(R.string.count_with_parentheses, "$count")
        }

    }

    private fun enableSubmit(isEnable: Boolean) {
        binding.tvSubmit.isEnabled = isEnable
        if (isEnable) {
            binding.tvSubmit.alpha = 1F
        } else {
            binding.tvSubmit.alpha = 0.4F
            binding.tvNumber.setText(null)

        }
    }

    companion object {

        fun create(context: Context, listener: OnReserveAllSelectListener): ReserveAllSelectPop {
            val inflater = LayoutInflater.from(context)
            return ReserveAllSelectPop(PopReserveAllSelectBinding.inflate(inflater), listener)
        }
    }

    interface OnReserveAllSelectListener {

        fun selectAll(isChecked: Boolean): Int

        fun submit()
    }
}