package com.adealink.weparty.room.widget

import android.content.Context
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.imageview.CircleRippleImageView
import com.adealink.weparty.module.room.data.SpeakingRippleConfig
import com.adealink.weparty.room.R

class SpeakingRippleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {

    private var config = SpeakingRippleConfig()
    private var baseSize = 0
    private var rippleRatio = 1f

    fun setBaseSize(size: Int) {
        this.baseSize = size
    }

    fun setRippleRatio(ratio: Float) {
        this.rippleRatio = ratio
    }

    fun setConfig(config: SpeakingRippleConfig) {
        this.config = config
    }

    fun startRipple() {
        inflateNormalRippleView().also {
            it.show()
            it.startRipple()
        }
    }

    fun stopRipple() {
        inflateNormalRippleView().also {
            it.stopRipple()
            it.gone()
        }
    }

    private fun inflateNormalRippleView(): CircleRippleImageView {
        var rippleView = findViewById<CircleRippleImageView>(R.id.id_mic_seat_speaking_normal_ripple_view)
        if (rippleView != null) {
            return rippleView
        }
        removeAllViews()
        rippleView = CircleRippleImageView(context).apply {
            id = R.id.id_mic_seat_speaking_normal_ripple_view
            setRippleColor(config.rippleColor)
            setRippleWidth(config.rippleWidth)
            setRippleSpace(config.rippleSpace)
            setRippleSpeed(config.rippleSpeed)
            setInnerBorderColor(config.innerBorderColor)
            innerBorderWidth = config.innerBorderWidth
            outerBorderWidth = ((baseSize * rippleRatio).toInt() - baseSize + 2) / 2
            setRippleEndAlphaDuration(config.rippleEndAlphaDuration)
            setRippleStartAlphaDuration(config.rippleStartAlphaDuration)
        }
        addView(
            rippleView,
            LayoutParams(
                (baseSize * rippleRatio).toInt(),
                (baseSize * rippleRatio).toInt()
            ).apply {
                startToStart = LayoutParams.PARENT_ID
                endToEnd = LayoutParams.PARENT_ID
                topToTop = LayoutParams.PARENT_ID
                bottomToBottom = LayoutParams.PARENT_ID
            }
        )
        return rippleView
    }


}