package com.base.browserwhite.ui.activity.download

import android.content.Intent
import android.graphics.Color
import androidx.activity.addCallback
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import com.base.browserwhite.bean.DownloadBean
import com.base.browserwhite.databinding.ActivityWebDownloadManagerBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.adapter.DownloadAdapter
import com.base.browserwhite.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.ui.views.DialogViews.showGerPermission
import com.base.browserwhite.ui.views.DialogViews.showMediaMoreDialog
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.DownloadHelper.getDownloadJson
import com.base.browserwhite.utils.DownloadHelper.getDownloadJsonBean
import com.base.browserwhite.utils.IntentEx.shareAction
import com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.PermissionHelp.checkStorePermission
import com.base.browserwhite.utils.PermissionHelp.requestStorePermission
import com.google.gson.Gson
import java.io.File

class WebDownloadManagerActivity : BaseActivity<ActivityWebDownloadManagerBinding>() {

    private lateinit var adapter: DownloadAdapter

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


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

        adapter = DownloadAdapter()
        adapter.moreAction = { archView, item ->
            showMediaMoreDialog(archView,
                deleteAction = {
                    showDeleteTipDialog {
                        runCatching {
                            File(item.path).delete()
                            saveDeleteJson(item)
                        }
                        adapter.remove(item)
                        val list = adapter.items.filter { !it.isTime && it.time == item.time }
                        if (list.isEmpty()) {
                            adapter.items.filter { it.isTime && it.time == item.time }.forEach { timeBean ->
                                adapter.remove(timeBean)
                            }
                            binding.llEmpty.isVisible = adapter.items.isEmpty()
                        }
                    }
                },
                shareAction = {
                    val uri = FileProvider.getUriForFile(this, "com.base.browserwhite.provider", File(item.path))
                    shareAction(uri, "video/*")
                })
        }
        binding.rv.adapter = adapter

        if (checkStorePermission()) {
            initData()
        } else {
            showGerPermission(desc = "", deny = { finishToMain() }, allow = {
                requestStorePermission(launcher, result = {
                    if (it) initData() else finishToMain()
                })
            })
        }
    }

    private fun saveDeleteJson(item: DownloadBean) {
        val recordFile = getDownloadJson()
        val list = getDownloadJsonBean(recordFile).toMutableList()
        list.removeIf { it.path == item.path }
        val json = Gson().toJson(list)
        recordFile.writeText(json)
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvHowUse.setOnClickListener {
            startActivity(Intent(this, WebDownloadGuideActivity::class.java))
            finish()
        }
    }

    private fun initData() {

        val list = getDownloadJsonBean(getDownloadJson())

        if (list.isEmpty()) {
            binding.llEmpty.isVisible = true
        } else {
            val beanList = arrayListOf<DownloadBean>()

            val timeList = arrayListOf<String>()
            list.sortedBy { it.time }.forEach { old ->
                val time = old.time.toFormatTime()
                if (!timeList.contains(time)) {
                    timeList.add(time)
                    beanList.add(DownloadBean(time = old.time).apply { isTime = true })
                }
                beanList.add(old.apply { uiType = 1 })
            }
            adapter.submitList(beanList)
        }

    }
}