package com.base.filerecoveryrecyclebin.service

import android.text.TextUtils
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinFileEx.getRecycleBinDir
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ironsource.da
import java.io.File
import java.util.stream.Collectors


object BackUpUtils {

    private const val KEY = "backup_key"


    fun backupFile(src: File, path: String) {
        val recycleBinFile = File(getRecycleBinDir(), ".\$name")
        src.copyTo(recycleBinFile, true)
        val binBean = RecycleBinBean(src.path, 0, src.length(), getFileExtension(src), false)
        saveData(binBean, path)
    }

    private fun getFileExtension(file: File): String {
        val fileName = file.name
        return if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            fileName.substring(fileName.lastIndexOf(".") + 1)
        } else {
            ""
        }
    }

    fun saveData(binBean: RecycleBinBean, path: String) {
        val hashMap = queryBackUpSp()
        hashMap.put(path, binBean)
        saveBackUpSp(hashMap)
    }

    fun queryBackUpSp(): HashMap<String, RecycleBinBean> {
        val str = AppPreferences.getInstance().getString(KEY, "")
        val hastMap: HashMap<String, RecycleBinBean>
        if (TextUtils.isEmpty(str)) {
            hastMap = HashMap()
        } else {
            val gson = Gson()
            // 使用TypeToken来指定HashMap的类型
            hastMap =
                gson.fromJson(str, object : TypeToken<HashMap<String, RecycleBinBean>>() {}.type)
        }
        return hastMap
    }

    fun saveBackUpSp(hash: HashMap<String, RecycleBinBean>) {
        AppPreferences.getInstance().put(KEY, Gson().toJson(hash))
    }

    fun getBackUpListObj(): List<RecycleBinBean>? {
        val hashMap = queryBackUpSp()
        if (hashMap.size > 0) {
            return null
        } else {
            val values: MutableList<RecycleBinBean>? =
                hashMap.values.stream().collect(Collectors.toList())
            return values
        }
    }

    fun queryFileExists(path: String): Boolean {
        val hashMap = queryBackUpSp()

        return hashMap.contains(path)
    }

    fun deleteFile(path: String) {
        val isExists = queryFileExists(path)
        if (isExists) {
            val hashMap =queryBackUpSp()
           val data = hashMap[path]
            if (data != null) {
                data?.deleted =true
                data?.deleteTime =System.currentTimeMillis()
                hashMap[path] = data
            }

        }
    }
}