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.activity.mediabrowser.MediaVideoDetailActivity
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.DownloadHelper.saveDownloadRecordFile
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 com.liulishuo.filedownloader.FileDownloader
import java.io.File

class WebDownloadManagerActivity : BaseActivity<ActivityWebDownloadManagerBinding>() {

    private lateinit var adapter: DownloadAdapter
    private val TAG = "WebDownloadManagerActivity"

    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 {
//                        adapter.items.forEach {
//                            LogEx.logDebug(TAG, "${it.isTime} ${it.time.toFormatTime()} ${it.path}")
//                        }
                        runCatching {
                            File(item.path).delete()
                            saveDeleteJson(item)
                        }
                        adapter.remove(item)
                        removeTimeDean(item)
                    }
                },
                shareAction = {
                    val uri = FileProvider.getUriForFile(this, "com.base.browserwhite.provider", File(item.path))
                    shareAction(uri, "video/*")
                })
        }
        adapter.itemClick = { path ->
            startActivity(Intent(this, MediaVideoDetailActivity::class.java).apply {
                putExtra("uri", path)
            })
        }
        binding.rv.adapter = adapter

        if (checkStorePermission()) {
            initData()
        } else {
            showGerPermission(
                desc = "This feature requires access to your storage to manage your downloads. We will not transfer your data to any third-party services. Please grant permission so that we can provide you with better services.",
                deny = { finishToMain() }, allow = {
                    requestStorePermission(launcher, result = {
                        if (it) initData() else finishToMain()
                    })
                })
        }
    }

    private fun removeTimeDean(item: DownloadBean) {

        val list = adapter.items.filter { !it.isTime && it.time.toFormatTime() == item.time.toFormatTime() }
        if (list.isEmpty()) {
            adapter.items.filter { it.isTime && it.time.toFormatTime() == item.time.toFormatTime() }.forEach { timeBean ->
                adapter.remove(timeBean)
            }
            binding.llEmpty.isVisible = adapter.items.isEmpty()
        }
    }

    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)
    }

    private fun clearDownloadJson() {
        val recordFile = getDownloadJson()
        recordFile.writeText("")
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvHowUse.setOnClickListener {
            startActivity(Intent(this, WebDownloadGuideActivity::class.java))
            finish()
        }
        binding.ivDelete.setOnClickListener {
            showDeleteTipDialog {
                runCatching {
                    adapter.items.forEach {
                        File(it.path).delete()
                        clearDownloadJson()
                    }
                }
                binding.llEmpty.isVisible = true
                binding.ivDelete.isEnabled = false
                adapter.submitList(listOf())
            }
        }
    }

    private fun initData() {

        val list = getDownloadJsonBean(getDownloadJson())


        if (list.isEmpty()) {
            binding.ivDelete.isEnabled = false
            binding.llEmpty.isVisible = true
        } else {
            val beanList = arrayListOf<DownloadBean>()
            beanList.forEach {
                it.status = FileDownloader.getImpl().getStatus(it.downloadId, it.path)
            }

            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)
            binding.ivDelete.isEnabled = true
        }

    }

    override fun onPause() {
        super.onPause()
        this.saveDownloadRecordFile(adapter.items)
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}