package com.base.datarecovery.activity

import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import androidx.activity.addCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.ads.admob.AdmobBannerUtils
import com.base.datarecovery.databinding.ActivityMainBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.FileHelp.getDirFiles
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.view.DialogViews.showExitDialog
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import com.base.datarecovery.view.PermissionDialog.showPermissionBottomSheet
import com.base.datarecovery.view.RateStarPop
import com.base.datarecovery.view.RateStarPop.showRateStarPopDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : BaseActivity<ActivityMainBinding>() {

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

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        if (!checkStorePermission()) {
            if (dialog == null) {
                dialog = showPermissionBottomSheet(launcher) {
                    AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flAd)
                }
            }
        } else {
            AdmobBannerUtils.showCollapsibleBannerAd(this, binding.flAd)
        }

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showExitDialog()
        }
    }

    override fun onResume() {
        super.onResume()

        lifecycleScope.launch(Dispatchers.Main) {
            delay(1000)
            showRateStarPopDialog()
        }
    }

    fun setScreenSize(action: (size: Long) -> Unit) {
        if (!checkStorePermission()) {
            action.invoke(0)
        } else {
            lifecycleScope.launch(Dispatchers.Main) {
                action.invoke(getScreenSize())
            }
        }
    }

    private suspend fun getScreenSize(): Long {
        val deferred = lifecycleScope.async(Dispatchers.IO) {
            val dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
            getDirFiles(dcim).sumOf { it.length() }
        }
        return deferred.await()
    }

}