import { convertKB } from '@/utils/file'
import { Storage } from '@/utils/storage'

/**
 * 图片 Hash 缓存标识前缀
 */
export const CACHE_PREFIX = 'G_CACHE_IMAGE__'

/**
 * 计算缓存大小
 * @returns 字节
 */
export function calculateCacheSize() {
    return Storage.keys()
        .filter((key) => key.startsWith(CACHE_PREFIX))
        .reduce((total, key) => {
            try {
                const cache = Storage.get(key)
                const result = JSON.parse(cache)
                total += result.size
            } catch (_) {}

            return total
        }, 0)
}

/**
 * 计算缓存大小格式化
 * @returns 格式化后的缓存大小
 * @example 1.2MB
 * @see {@link calculateCacheSize}
 * @see {@link convertKB}
 * @see {@link CACHE_PREFIX}
 */
export function calculateCacheSizeFormat() {
    const cacheSize = calculateCacheSize()
    const { size, unit } = convertKB(cacheSize)
    return `${size}${unit}`
}

/**
 * 清理缓存
 */
export function cleanCache() {
    const promises = Storage.keys()
        .filter((key) => key.startsWith(CACHE_PREFIX))
        .map((key) => {
            return new Promise((resolve, reject) => {
                try {
                    const cache = Storage.get(key)
                    const result = JSON.parse(cache)
                    uni.removeSavedFile({
                        filePath: result.url,
                        complete: resolve,
                    })
                } catch (e) {
                    console.error(e)
                    reject(e)
                } finally {
                    Storage.remove(key)
                }
            })
        })

    return Promise.allSettled(promises)
}
