package com.base.browserwhite.utils

import android.content.Context
import android.os.Environment
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.R
import com.base.browserwhite.bean.DownloadBean
import com.base.browserwhite.bean.downloadBeanGson
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.model.FileDownloadStatus
import java.io.File
import java.lang.reflect.Type

object DownloadHelper {

    private val TAG = "DownloadHelper"
    fun Context.getDownloadJson(): File {
        val file = File(this.filesDir, "downloadRecord")
        val recordFile = File(file, "download.json")
        if (!file.exists()) {
            file.mkdirs()
        }
        if (!recordFile.exists()) {
            recordFile.createNewFile()
        }
        return recordFile
    }

    fun getDownloadJsonBean(recordFile: File, gson: Gson = downloadBeanGson): List<DownloadBean> {
        val olderText = recordFile.readText()
        val type: Type = object : TypeToken<List<DownloadBean>>() {}.type
        return gson.fromJson<List<DownloadBean>?>(olderText, type) ?: listOf()
    }

    fun Context.getDownloadPath(
        item: DownloadBean
    ): String {

        // 设置下载文件的存储位置
        val dirPath = File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), resources.getString(R.string.app_name)
        ).absolutePath

        val dirFile = File(dirPath)
        if (!dirFile.exists()){
            dirFile.mkdirs()
        }

        if (item.status == FileDownloadStatus.paused) {
            return "$dirPath/${item.name}"
        }

        var fileName = item.url.split("/").last()
        if (item.name.isNotEmpty()) {
            fileName = item.name
        }

        var path = "$dirPath/$fileName"
        while (File(path).exists()) {
            val split = File(path).name.split(".")
            val suffix = split[1]
            var cname = split[0]
            LogEx.logDebug("getDownloadPath", "cname=$cname")
            val char = cname.last()
            if (char.isDigit()) {
                cname = cname.substring(0, cname.length - 1) + (char + 1)
            } else {
                cname += "1"
            }
            path = "$dirPath/$cname.$suffix"
            item.name = "$cname.$suffix"
            LogEx.logDebug("getDownloadPath", "path=$path")
        }
        return path
    }

    fun Context.saveDownloadRecordFile(downloadList: List<DownloadBean>) = Thread {

        val recordFile = getDownloadJson()

        //已开始的任务
        val startedList = downloadList.filter {
            (it.status == FileDownloadStatus.progress || it.status == FileDownloadStatus.paused) && !it.isTime
        }

        startedList.forEach { it.time = System.currentTimeMillis() }
        val startPath = startedList.map { it.path }

        //完成的任务
        val finishList = downloadList.filter { it.status == FileDownloadStatus.completed && !it.isTime }
        val finishPath = finishList.map { it.path }


        //以前的去除重叠的
        val olderList = getDownloadJsonBean(recordFile, downloadBeanGson).toMutableList()
        olderList.removeIf { startPath.contains(it.path) }
        olderList.removeIf { finishPath.contains(it.path) }
        olderList.forEach {
            it.status = FileDownloader.getImpl().getStatus(it.downloadId, it.path)
        }

        val arrayList = arrayListOf<DownloadBean>()
        arrayList.addAll(olderList)
        arrayList.addAll(startedList)
        arrayList.addAll(finishList)

        arrayList.forEach {
            LogEx.logDebug(TAG, "saveDownloadRecordFile ${it.name} ${it.downloadId} ${it.status} ${it.path}")
        }

        val json = downloadBeanGson.toJson(arrayList)
        recordFile.writeText(json)
    }.start()


}