package com.adealink.weparty.commonui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import androidx.constraintlayout.widget.ConstraintLayout
import com.adealink.weparty.databinding.WidgetLoadingBinding

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

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

    private var loadingAnimation: Animation? = null

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        val animation = RotateAnimation(
            0f,
            360f,
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        ).apply {
            duration = 400
            repeatMode = Animation.RESTART
            repeatCount = Animation.INFINITE
            interpolator = LinearInterpolator()
            start()
        }.also {
            loadingAnimation = it
        }
        binding.ivLoading.animation = animation
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        loadingAnimation?.cancel()
        loadingAnimation = null
    }

}