package com.zxhyis.toolss.ui.page.speed

import android.animation.Animator
import android.content.Intent
import android.graphics.Color
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.zxhyis.toolss.ad.ConfigHelper
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityLayoutSpeedBinding
import com.zxhyis.toolss.ui.AFunOb.APPP_SPEED
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

class SpeedActivity : TopActivity<ActivityLayoutSpeedBinding>() {
    override fun getViewBinding1(): ActivityLayoutSpeedBinding {
        return ActivityLayoutSpeedBinding.inflate(layoutInflater)
    }

    override fun init() {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        vb.root.updatePadding(top = BarUtils.getStatusBarHeight())
        vb.idOneLottie.imageAssetsFolder = "appmanager/images/"
        vb.idOneLottie.setAnimation("appmanager/data.json")
        vb.idOneLottie.playAnimation()
        vb.root.postDelayed({
            vb.idOneLottie.isVisible = false
            vb.idScaning.text = "Optimizing"

            playRocket()
        }, 3000)
    }

    private fun playRocket() {
        vb.idRocket.imageAssetsFolder = "fast/images/"
        vb.idRocket.setAnimation("fast/data.json")
        vb.idRocket.playAnimation()
        MainScope().launch(Dispatchers.Main) {
            launch {
                if (ConfigHelper.appList.isNullOrEmpty()) {
                    withContext(Dispatchers.IO) {
                        ConfigHelper.appList = AppUtils.getAppsInfo().shuffled()
                    }
                }
                val icons = ConfigHelper.appList?.filter { !it.isSystem }?.map { it.icon }
                var index = 0
                vb.idSpeedIcon.isVisible = true
                while (vb.idRocket.isVisible) {
                    vb.idSpeedIcon.setImageDrawable(icons?.getOrNull(index++ % icons.size))
                    delay(Random.nextLong(100, 200))
                }
            }
        }
        vb.idRocket.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(p0: Animator) {

            }

            override fun onAnimationEnd(p0: Animator) {
                startActivity(Intent(this@SpeedActivity, SpeedFinishActivity::class.java).putExtra("type",APPP_SPEED))
                finish()
            }

            override fun onAnimationCancel(p0: Animator) {

            }

            override fun onAnimationRepeat(p0: Animator) {

            }

        })
    }
}