package com.img.rabbit.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.usage.StorageStatsManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.storage.StorageManager
import android.provider.Settings
import android.text.format.Formatter
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.io.File
import java.util.UUID

// 创建DataStore实例
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_settings")

// DataStore键定义
object AppPreferencesKeys {
    val NAVIGATION_BAR_VISIBLE = booleanPreferencesKey("navigation_bar_visible")
    val USER_LOGGED_IN = booleanPreferencesKey("user_logged_in")
}

class AppDataStore(private val context: Context) {

    // 获取NavigationBar显示状态
    val isNavigationBarVisible: Flow<Boolean> = context.dataStore.data
        .map { preferences ->
            preferences[AppPreferencesKeys.NAVIGATION_BAR_VISIBLE] ?: true
        }

    // 设置NavigationBar显示状态
    suspend fun setNavigationBarVisible(visible: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[AppPreferencesKeys.NAVIGATION_BAR_VISIBLE] = visible
        }
    }

    // 获取用户登录状态
    val isUserLoggedIn: Flow<Boolean> = context.dataStore.data
        .map { preferences ->
            preferences[AppPreferencesKeys.USER_LOGGED_IN] ?: false
        }

    // 设置用户登录状态
    suspend fun setUserLoggedIn(loggedIn: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[AppPreferencesKeys.USER_LOGGED_IN] = loggedIn
        }
    }
}

object AppDataStoreUtils {
    fun getAppStorageStats(context: Context,onResult:(appSize:String,cacheSize:String,dataSize:String,totalDataCacheSize:String)->Unit) {
        var cacheSize = "0MB"
        var dataSize = "0MB"
        var totalDataCacheSize = "0MB"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val storageStatsManager = context.getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager

            val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager

            // 获取应用所在的存储卷 UUID (通常是内部存储)
            val uuid: UUID = storageManager.getUuidForPath(context.filesDir)

            // 查询当前应用的统计信息
            val stats = storageStatsManager.queryStatsForUid(uuid, context.applicationInfo.uid)

            // 格式化为易读字符串 (如 10.5 MB)
            //val appSize = Formatter.formatFileSize(context, stats.appBytes)     // 应用本身 (APK等)
            dataSize = Formatter.formatFileSize(context, stats.dataBytes)   // 用户数据 (包含缓存)
            cacheSize = Formatter.formatFileSize(context, stats.cacheBytes) // 仅缓存数据
            totalDataCacheSize = Formatter.formatFileSize(context, stats.dataBytes + stats.cacheBytes) // 数据缓存 (如数据库缓存)
        }else{
            // 1. 缓存大小 (Cache): 包括内部缓存和外部缓存
            val internalCache = getFolderSize(context.cacheDir)
            val externalCache = getFolderSize(context.externalCacheDir)
            val totalCache = internalCache + externalCache

            // 2. 数据大小 (Data): 通常指 files、databases、shared_prefs 等
            val filesDirSize = getFolderSize(context.filesDir)
            val dbDir = context.getDatabasePath("dummy").parentFile // 获取数据库根目录
            val databasesSize = getFolderSize(dbDir)
            val prefsSize = getFolderSize(File(context.filesDir.parent, "shared_prefs"))

            val totalUserData = filesDirSize + databasesSize + prefsSize

            // 格式化显示
            cacheSize = Formatter.formatFileSize(context, totalCache)
            dataSize = Formatter.formatFileSize(context, totalUserData)
            totalDataCacheSize = Formatter.formatFileSize(context, totalCache + totalUserData)
        }

        onResult("",dataSize, cacheSize, totalDataCacheSize)
    }

    /**
     * 递归计算文件夹或文件的大小
     */
    fun getFolderSize(file: File?): Long {
        if (file == null || !file.exists()) return 0L

        var size: Long = 0
        val fileList = file.listFiles() ?: return file.length() // 如果是文件直接返回长度

        for (subFile in fileList) {
            size += if (subFile.isDirectory) {
                getFolderSize(subFile) // 递归遍历子目录
            } else {
                subFile.length()
            }
        }
        return size
    }

    /**
     * 引导用户打开应用设置页面（手动清除）
     */
    fun openAppSettings(context: Context) {

        try {
            // 尝试直接进入存储详情页
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = android.net.Uri.fromParts("package", context.packageName, null)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果直达失败，降级跳转到应用详情主页
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = android.net.Uri.fromParts("package", context.packageName, null)
            }
            context.startActivity(intent)
        }
    }

    /**
     * 直接清除应用数据（包括缓存和数据库）
     */
    fun clearAppData(context: Context) {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        // 这一步会直接清除所有私有数据并结束进程
        val isSuccess = activityManager.clearApplicationUserData()
    }
}
