package com.base.filerecoveryrecyclebin.service

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils
import android.util.Log
import androidx.core.content.ContextCompat
import com.base.filerecoveryrecyclebin.MyApplication
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinFileEx.getRecycleBinDir
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.lang.Exception
import java.util.stream.Collectors


object BackUpUtils {

    private const val KEY = "backup_key"


    fun backupFile(src: File, path: String) {
        if (!hasStorageReadWritePermission()) {
            return
        }
        try {
            val recycleBinFile = File(getRecycleBinDir(), ".$path")
            src.copyTo(recycleBinFile, true)
            val binBean = RecycleBinBean(path,src.path, recycleBinFile.absolutePath,0, src.length(), getFileExtension(src), false)
            saveData(binBean, path)
        } catch (e: Exception) {

        }

    }

    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>) {
        val str = Gson().toJson(hash)
        Log.d("FileObserverExample", str)
        AppPreferences.getInstance().put(KEY, str)
    }

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

    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
                saveBackUpSp(hashMap)
            }

        }
    }


    /**
     * 检查应用是否具有存储读写权限
     *
     * @param context 应用上下文
     * @return 如果应用有权限返回 true，否则返回 false
     */
    fun hasStorageReadWritePermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return true
        } else {
            // 检查存储读写权限
            val readPermission: Int = ContextCompat.checkSelfPermission(
                BaseApplication.context,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            val writePermission: Int = ContextCompat.checkSelfPermission(
                BaseApplication.context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED
        }
    }
}