package com.audio.record.screen.test.view
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.*
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.TextView
import com.audio.record.screen.test.R

object CountDownFloatingManager {

    private var countdownView: View? = null
    private var handler: Handler? = null

    fun show(context: Context, onFinish: (() -> Unit)? = null) {
        if (countdownView != null) return // Already showing

        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val inflater = LayoutInflater.from(context)
        countdownView = inflater.inflate(R.layout.floating_view_countdown, null)
        val tvCountdown = countdownView!!.findViewById<TextView>(R.id.tv_countdown)

        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
            PixelFormat.TRANSLUCENT
        )
        layoutParams.gravity = Gravity.CENTER

        windowManager.addView(countdownView, layoutParams)

        val countdownValues = arrayOf("3", "2", "1")
        var index = 0

        handler = Handler(Looper.getMainLooper())

        fun animateNext() {
            if (index >= countdownValues.size) {
                remove(windowManager)
                onFinish?.invoke()
                return
            }

            tvCountdown.text = countdownValues[index]
            tvCountdown.scaleX = 0f
            tvCountdown.scaleY = 0f
            tvCountdown.alpha = 0f

            tvCountdown.animate()
                .scaleX(1f).scaleY(1f)
                .alpha(1f)
                .setDuration(400)
                .setInterpolator(AccelerateDecelerateInterpolator())
                .withEndAction {
                    handler?.postDelayed({
                        index++
                        animateNext()
                    }, 600)
                }
                .start()
        }

        animateNext()
    }

    fun remove(windowManager: WindowManager) {
        handler?.removeCallbacksAndMessages(null)
        handler = null
        countdownView?.let {
            try {
                windowManager.removeView(it)
            } catch (e: Exception) {
                // view already removed
            }
        }
        countdownView = null
    }


}