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

import android.content.Intent
import android.graphics.Color
import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import com.base.browserwhite.R
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.showGerPermission
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.DownloadHelper.getDownloadJson
import com.base.browserwhite.utils.DownloadHelper.getNotFinishList
import com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.PermissionHelp.checkStorePermission
import com.base.browserwhite.utils.PermissionHelp.requestStorePermission
import com.downloader.Status
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()
        binding.rv.adapter = adapter

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

    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 appName: String = resources.getString(R.string.app_name)
        val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), appName)
        if (dir.listFiles().isNullOrEmpty()) {
            binding.llEmpty.isVisible = true
        } else {
            val fileList = arrayListOf<File>()
            val timeList = arrayListOf<String>()
            val beanList = arrayListOf<DownloadBean>()
            fileList.addAll(dir.listFiles() ?: arrayOf())
            fileList.sortBy { it.lastModified() }

            fileList.forEach {
                val time = it.lastModified().toFormatTime()
                if (!timeList.contains(time)) {
                    timeList.add(time)
                    beanList.add(DownloadBean(time = time).apply { isTime = true })
                } else {
                    beanList.add(DownloadBean(path = it.absolutePath))
                }
            }

            getNotFinishList(getDownloadJson()).forEach { old ->
                if (!timeList.contains(old.time)) {
                    timeList.add(old.time)
                    beanList.add(DownloadBean(time = old.time).apply { isTime = true })
                }
                val index = beanList.indexOfFirst { bean -> bean.time == old.time }
                runCatching {
                    beanList.add(index + 1, old)
                }
            }
            adapter.submitList(beanList)
        }


    }
}