package com.adealink.weparty.commonui.widget.switchbutton

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatImageView
import com.adealink.weparty.R

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

    var checkChangedListener: OnCheckChangedListener? = null

    @DrawableRes
    var checkedDrawableResId = R.drawable.commonui_switch_button_checked_ic

    @DrawableRes
    var unCheckedDrawableResId = R.drawable.commonui_switch_button_un_checked_ic

    private var isChecked: Boolean = false

    init {
        val typedArray: TypedArray = context.obtainStyledAttributes(
            attrs,
            R.styleable.SwitchButton
        )
        checkedDrawableResId = typedArray.getResourceId(R.styleable.SwitchButton_checked_drawable,
            checkedDrawableResId)
        typedArray.getResourceId(R.styleable.SwitchButton_un_checked_drawable,
            unCheckedDrawableResId)
        this.isChecked = typedArray.getBoolean(R.styleable.SwitchButton_is_checked, isChecked)
        setImageResource(if (isChecked) checkedDrawableResId else unCheckedDrawableResId)
        typedArray.recycle()
        setOnClickListener {
            setChecked(!isChecked, true)
        }
    }

    fun setChecked(isChecked: Boolean) {
        setChecked(isChecked, false)
    }

    fun isChecked(): Boolean = isChecked

    private fun setChecked(isChecked: Boolean, fromUser: Boolean = false) {
        if (this.isChecked == isChecked) {
            return
        }

        this.isChecked = isChecked
        setImageResource(if (isChecked) checkedDrawableResId else unCheckedDrawableResId)
        checkChangedListener?.onChecked(isChecked, fromUser)
    }

    interface OnCheckChangedListener {

        fun onChecked(isChecked: Boolean, fromUser: Boolean)

    }

}