package com.base.datarecovery.activity.repeat

import android.content.Intent
import android.widget.Toast
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.databinding.ActivityRepeatAnimationBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.utils.SimarPhotoUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.random.Random

class RepeatAnimationActivity : BaseActivity<ActivityRepeatAnimationBinding>() {

    override val binding: ActivityRepeatAnimationBinding by lazy {
        ActivityRepeatAnimationBinding.inflate(layoutInflater)
    }

    private var job: Job? = null

    override fun initView() {
        AdmobMaxHelper.admobMaxShowNativeAd(this, binding.idFlNative, 1)
    }

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

//    fun jumpJob() = lifecycleScope.launch {
//        delay(Random.nextLong(3000, 4500))
//        AdmobMaxHelper.admobMaxShowInterstitialAd(this@RepeatAnimationActivity) {
//            startActivity(Intent(this@RepeatAnimationActivity, RepeatActivity::class.java))
//            finish()
//        }
//    }
//
//    override fun onResume() {
//        super.onResume()
//        if (job?.isActive == false || job == null) {
//            job = jumpJob()
//        }
//    }
//
//    override fun onPause() {
//        super.onPause()
//        job?.cancel()
//        job = null
//    }

    private var isPasue = false
    override fun onPause() {
        super.onPause()
        isPasue = false

    }

    override fun onResume() {
        super.onResume()
        isPasue = true
        playAnimal()
    }
    private fun playAnimal() {
        lifecycleScope.launch(Dispatchers.Main) {
            binding.root.postDelayed({
                SimarPhotoUtils.getImageFiles {
                    animaEnd()
                }

            }, Random.nextLong(500, 1000))
        }
    }
    private fun animaEnd(){
        if (isPasue) {

            AdmobMaxHelper.admobMaxShowInterstitialAd(this){
                startActivity(Intent(this, SimilarPicAt::class.java))
                finish()
            }
        }
    }
}