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.base.filerecoveryrecyclebin.utils.LogEx
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 val TAG = "FileObserverExample"
    private const val KEY = "backup_key"


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

        }
    }


    fun deleteFile(path: String) {
        if (path.isEmpty()) return
        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)
            }

        }
    }

    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, namePath: String) {
        if (namePath.isEmpty()) return
        val hashMap = queryBackUpSp()
        hashMap.put(namePath, 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(TAG, 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(namePath: String): Boolean {
        val hashMap = queryBackUpSp()
        return hashMap.contains(namePath)
    }

    fun deleteFileSp(namePath: String) {
        val map = queryBackUpSp()
        map.remove(namePath)
        saveBackUpSp(map)
    }


    /**
     * 检查应用是否具有存储读写权限
     *
     * @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
        }
    }

    fun recoveryFile(name: String) {
        val isExists = queryFileExists(name)
        if (isExists) {
            val hashMap = queryBackUpSp()
            hashMap.remove(name)
            saveBackUpSp(hashMap)
        }
    }
}