package com.base.browserwhite.utils

import android.content.Context
import android.os.Environment
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 java.io.File
import java.lang.reflect.Type

object 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)?.filter { File(it.path).exists() } ?: listOf()
    }

    fun Context.getDownloadPath(
        url: String,
        name: String,
    ): String {
        var fileName = url.split("/").last()
        if (name.isNotEmpty()) {
            fileName = name
        }
        // 设置下载文件的存储位置
        val dirPath = File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), resources.getString(R.string.app_name)
        ).absolutePath

        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"
            LogEx.logDebug("getDownloadPath", "path=$path")
        }
        return path
    }


}