package com.adealink.weparty.commonui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.withStyledAttributes
import com.adealink.weparty.R
import com.adealink.weparty.databinding.LayoutNumberIncreaseViewBinding
import kotlin.math.max
import kotlin.math.min

class NumberIncreaseView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    companion object {
        private const val MIN_NUMBER = 0
        private const val MAX_NUMBER = 99
    }

    private val binding =
        LayoutNumberIncreaseViewBinding.inflate(LayoutInflater.from(context), this)

    private var number = 0

    init {
        context.withStyledAttributes(
            attrs,
            R.styleable.NumberIncreaseView
        ) {
            number = getInt(
                R.styleable.NumberIncreaseView_default_number,
                0
            ).coerceIn(MIN_NUMBER, MAX_NUMBER)
        }

        binding.tvNumber.text = number.toString()
        binding.ivMinus.setOnClickListener {
            clickMinus()
        }
        binding.ivAdd.setOnClickListener {
            clickAdd()
        }
    }

    private fun clickMinus() {
        number = max(MIN_NUMBER, number - 1)
        binding.tvNumber.text = number.toString()
        if (number <= MIN_NUMBER) {
            binding.ivMinus.setImageResource(R.drawable.common_number_minus_diable_ic)
        } else {
            binding.ivMinus.setImageResource(R.drawable.common_number_minus_ic)
        }
    }

    private fun clickAdd() {
        number = min(MAX_NUMBER, number + 1)
        binding.tvNumber.text = number.toString()
    }

    fun getNumber(): Int {
        return number
    }

}