package com.base.datarecovery.activity.battery

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import android.widget.Toast
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.databinding.ActivityBatteryInfoAnimationBinding
import com.base.datarecovery.help.BaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

class BatteryInfoAnimationActivity : BaseActivity<ActivityBatteryInfoAnimationBinding>() {

    override val binding: ActivityBatteryInfoAnimationBinding by lazy {
        ActivityBatteryInfoAnimationBinding.inflate(layoutInflater)
    }
    private var job: Job? = null

    override fun initView() {
        resumeLottie()
    }

    override fun initListener() {
        onBackPressedDispatcher.addCallback {
            Toast.makeText(this@BatteryInfoAnimationActivity, "wait a moment", Toast.LENGTH_SHORT).show()
        }
    }


    override fun onPause() {
        super.onPause()
        binding.lottie.pauseAnimation()
        job?.cancel()
        job = null
    }

    override fun onResume() {
        super.onResume()
        resumeLottie()
        if (job?.isActive == false || job == null) {
            job = waitJob()
        }

    }

    private fun resumeLottie() {
        binding.lottie.imageAssetsFolder = "battery_scan/images/"
        binding.lottie.setAnimation("battery_scan/data.json")
        binding.lottie.playAnimation()
    }

    @SuppressLint("SetTextI18n")
    private fun waitJob() = lifecycleScope.launch(Dispatchers.Main) {
        delay(Random.nextLong(3000, 4500))
        binding.lottie.visibility = View.GONE
        binding.lottieCompleted.visibility = View.VISIBLE
        binding.lottieCompleted.playAnimation()
        binding.tv.text = "Completed!"
        delay(1000)
        AdmobMaxHelper.admobMaxShowOpenAd(this@BatteryInfoAnimationActivity, showBeforeAction = {}) {
            binding.lottie.clearAnimation()
            startActivity(Intent(this@BatteryInfoAnimationActivity, BatteryActivity::class.java))
            finish()
        }
    }

}