package com.remax.visualnovel.widget.ui

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.view.isVisible
import com.remax.visualnovel.R
import com.remax.visualnovel.utils.spannablex.utils.dp
import com.remax.visualnovel.widget.uitoken.expend.dsl.expandDp
import androidx.core.content.withStyledAttributes

/**
 * Created by HJW on 2022/8/31
 *
 */
class CheckBoxButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    View(context, attrs, defStyleAttr) {

    private val viewSize = 20.dp

    var isChecked = false

    init {
        context.withStyledAttributes(attrs, R.styleable.CheckBoxButton) {
            isChecked = getBoolean(R.styleable.CheckBoxButton_radioCheck, false)
        }
        expandDp(14, 14)
        viewChecked(isChecked)
    }

    override fun setVisibility(visibility: Int) {
        super.setVisibility(visibility)
        if (isVisible) {
            expandDp(14, 14)
        }
    }

    override fun setEnabled(enabled: Boolean) {
        super.setEnabled(enabled)
        if (enabled) {
            viewChecked(isChecked)
        } else {
            setBackgroundResource(R.mipmap.icon_multi_checked_disabled)
        }
    }

    fun viewChecked(isChecked: Boolean) {
        this.isChecked = isChecked
        if (isChecked) {
            setBackgroundResource(R.mipmap.icon_multi_checked)
        } else {
            setBackgroundResource(R.mipmap.checkbox_normal)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
            setMeasuredDimension(widthMeasureSpec, heightMeasureSpec)
        } else {
            setMeasuredDimension(viewSize, viewSize)
        }
    }
}