package com.base.filerecoveryrecyclebin.activity.largefile

import android.annotation.SuppressLint
import android.content.Intent
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.activity.ResultActivity
import com.base.filerecoveryrecyclebin.adapter.LargeFileAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.ConstObject
import com.base.filerecoveryrecyclebin.bean.ConstObject.SELECT_FILE_ALL
import com.base.filerecoveryrecyclebin.bean.ConstObject.SELECT_FILE_AUDIO
import com.base.filerecoveryrecyclebin.bean.ConstObject.SELECT_FILE_DOCUMENT
import com.base.filerecoveryrecyclebin.bean.ConstObject.SELECT_FILE_OTHER
import com.base.filerecoveryrecyclebin.bean.ConstObject.SELECT_FILE_PICTURE
import com.base.filerecoveryrecyclebin.bean.ConstObject.SELECT_FILE_VIDEO
import com.base.filerecoveryrecyclebin.bean.MediaBean
import com.base.filerecoveryrecyclebin.databinding.ActivityLargeFileBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.help.MediaStoreHelp.getAllMedia
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.help.PermissionHelp.requestStorePermission
import com.base.filerecoveryrecyclebin.view.DialogViews.showDeletePermanentlyDialog
import com.base.filerecoveryrecyclebin.view.DialogViews.showExitFunctionDialog
import com.base.filerecoveryrecyclebin.view.DialogViews.showGerPermission
import com.base.filerecoveryrecyclebin.view.DialogViews.showLargeFileTypeDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class LargeFileActivity : BaseActivity<ActivityLargeFileBinding>() {

    private lateinit var largeFileAdapter: LargeFileAdapter
    private var largeData = listOf<MediaBean>()

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

    var selectType = SELECT_FILE_ALL


    @SuppressLint("SetTextI18n")
    override fun initView() {
        largeFileAdapter = LargeFileAdapter(itemClick = {}, selectClick = {
            if (it.isNotEmpty()) {
                binding.tvDelete.isEnabled = true
                binding.tvDelete.text = "Delete(${it.sumOf { bean -> bean.size }.toFormatSize()})"
            } else {
                binding.tvDelete.isEnabled = false
            }
        })
        binding.rv.adapter = largeFileAdapter

        if (checkStorePermission()) {
            initData()
        } else {
            showGerPermission(
                desc = "This feature requires access to your storage to scan your large files and clean up large files." +
                        "We will not transmit your data to any third-party service. Please grant permission so that we can provide you with better service.",
                deny = { finishToMain() },
                allow = {
                    requestStorePermission(launcher) {
                        if (it) initData() else finishToMain()
                    }
                })
        }
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog { show ->
                if (show) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this@LargeFileActivity, isLoading = false) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }
            }
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvDelete.setOnClickListener {
            showDeletePermanentlyDialog {
                deleteFiles()
            }
        }
        binding.flFilter.setOnClickListener {
            showLargeFileTypeDialog(selectType) { type ->
                selectType = type
                binding.tvType.text = selectType
                largeFileAdapter.setData(largeData.filter { selectFilter(it) })
            }
        }
    }

    private fun selectFilter(mediaBean: MediaBean): Boolean {

        when (selectType) {
            SELECT_FILE_ALL -> return true
            SELECT_FILE_PICTURE -> {
                return mediaBean.mimeType.contains("image")
            }

            SELECT_FILE_VIDEO -> {
                return mediaBean.mimeType.contains("video")
            }

            SELECT_FILE_AUDIO -> {
                return mediaBean.mimeType.contains("audio")
            }

            SELECT_FILE_DOCUMENT -> {
                return mediaBean.mimeType.contains("pdf")
                        || mediaBean.mimeType.contains("msword")
                        || mediaBean.mimeType.contains("document")
                        || mediaBean.mimeType.contains("excel")
                        || mediaBean.mimeType.contains("sheet")
                        || mediaBean.mimeType.contains("powerpoint")
                        || mediaBean.mimeType.contains("presentation")
            }

            SELECT_FILE_OTHER -> {
                return mediaBean.mimeType.contains("zip")
                        || mediaBean.mimeType.contains("rar")
                        || mediaBean.mimeType.contains("7z")
                        || mediaBean.mimeType.contains("tar")
                        || mediaBean.mimeType.contains("archive")
                        || mediaBean.mimeType.contains("stream")
            }
        }

        return false
    }

    private fun deleteFiles() = lifecycleScope.launch(Dispatchers.IO) {

        val list = largeFileAdapter.getSelectData()
        runCatching {
            list.forEach { bean ->
                File(bean.path).delete()
            }
        }
        launch(Dispatchers.Main) {
            largeFileAdapter.removeData(list)
            delay(1000)
            startActivity(Intent(this@LargeFileActivity, ResultActivity::class.java).apply {
                putExtra("from", ConstObject.LARGE_FILE)
            })
            finish()
        }
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val beanList = getAllMedia { size -> size > 1024 * 1024 * 50 }
        launch(Dispatchers.Main) {
            largeData = beanList
            binding.llEmpty.isVisible = beanList.isEmpty()
            largeFileAdapter.setData(beanList)
        }
    }

}