package com.adealink.weparty.commonui.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.adealink.weparty.commonui.drawabletoolbox.FluidColorfulFrameDrawable

class FluidFrameView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatImageView(context, attrs) {
    private var drawable: FluidColorfulFrameDrawable? = null

    fun setFluidFrameDrawable(drawable: FluidColorfulFrameDrawable) {
        this.drawable?.callback = null
        this.drawable = drawable.also {
            it.callback = this@FluidFrameView
        }
    }

    fun getFluidFrameDrawable(): FluidColorfulFrameDrawable? {
        return this.drawable
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        val d = drawable ?: return
        d.setBounds(0, 0, w, h)
        d.cancelFluid()
        d.startFluid()
    }

    fun startFluid() {
        val d = drawable ?: return
        if (d.isFluiding()) {
            return
        }
        if (d.isFluidStarted()) {
            d.resumeFluid()
        } else {
            d.startFluid()
        }
    }

    fun cancelFluid() {
        drawable?.cancelFluid()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawable?.draw(canvas)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        drawable?.cancelFluid()
    }

    override fun invalidateDrawable(dr: Drawable) {
        super.invalidateDrawable(dr)
        if (dr === drawable) {
            invalidate()
        }
    }
}