package com.base.datarecovery.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.adapter.ScreenShotAdapter
import com.base.datarecovery.ads.AdmobInterstitialUtils
import com.base.datarecovery.bean.ScreenPhotoBean
import com.base.datarecovery.bean.ScreenshotBean
import com.base.datarecovery.databinding.ActivityScreenShotBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.FileHelp
import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.help.PermissionHelp.requestStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.view.DialogViews.showGerPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale
import kotlin.collections.HashSet

class ScreenShotActivity : BaseActivity<ActivityScreenShotBinding>() {

    private lateinit var screenShotAdapter: ScreenShotAdapter

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

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        screenShotAdapter = ScreenShotAdapter { size ->
            setCleanUpUi(size)
        }

        binding.rv.adapter = screenShotAdapter

        if (checkStorePermission()) {
            initData()
        } else {
            dialog = showGerPermission(null, deny = {},
                allow = {
                    requestStorePermission(launcher, result = { flag ->
                        if (flag) initData() else finishToMain()
                    })
                })
        }

    }


    @SuppressLint("SetTextI18n")

    private fun setCleanUpUi(size: Int) {
        if (size > 0) {
            binding.tvClean.isEnabled = true
            binding.tvClean.text = "CLEAN(${size})"
        } else {
            binding.tvClean.isEnabled = false
            binding.tvClean.text = "CLEAN"
        }
        binding.llSelectAll.isSelected = screenShotAdapter.isAllSelect()
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = getScreenshotBean()
        launch(Dispatchers.Main) {
            screenShotAdapter.setData(list)
            val size = list.sumOf { it.screenPhotoBean.sumOf { ss -> ss.file.length() } }
            val sizeF = size.toFormatSize().split(" ")
            binding.tvSize.text = sizeF[0]
            binding.tvUnit.text = sizeF[1]
        }
    }

    override fun initListener() {
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            AdmobInterstitialUtils.showInterstitialAd(this@ScreenShotActivity) {
                finishToMain()
            }
        }


        binding.llSelectAll.setOnClickListener {
            binding.llSelectAll.isSelected = !binding.llSelectAll.isSelected
            screenShotAdapter.toggleSelect(binding.llSelectAll.isSelected)
            val size = screenShotAdapter.getSelectDataSize()
            setCleanUpUi(size)
        }
        binding.tvClean.setOnClickListener {
            val files = screenShotAdapter.getSelectData()
            AdmobInterstitialUtils.showInterstitialAd(this) {
                lifecycleScope.launch(Dispatchers.IO) {
                    async {
                        files.forEach { screenFile ->
                            runCatching {
                                val file = screenFile.file
                                if (file.exists()) file.delete()
                            }
                        }
                    }.await()
                    launch(Dispatchers.Main) {
                        screenShotAdapter.removeData(files)
                    }
                }
            }
        }

    }

    private fun getScreenshotBean(): ArrayList<ScreenshotBean> {
        val dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        val screenFiles = FileHelp.getDirFiles(dcim)
        val hash = HashMap<String, HashSet<File>>()
        val formatter = SimpleDateFormat("yyyy/MM", Locale.getDefault())

        screenFiles.forEach { file ->
            val time = formatter.format(file.lastModified())
            if (hash[time] == null) {
                hash[time] = HashSet()
            }
            val set = hash[time]
            set?.add(file)
        }

        val beans = arrayListOf<ScreenshotBean>()
        hash.forEach { (t, u) ->
            val arrayList = arrayListOf<ScreenPhotoBean>()
            val mapList = u.map { file -> ScreenPhotoBean(file) }
            arrayList.addAll(mapList)
            beans.add(ScreenshotBean(t, arrayList))
        }
        return beans
    }
}