// import RNDeviceInfo from 'react-native-device-info';
import * as fs from 'expo-file-system/legacy';

import { createMMKV, MMKV } from 'react-native-mmkv';

const TTL_KEY = '$__$t_';
function fixPath(path: string) {
    if (path.startsWith("file:///")) {
        return path.substring(7);
    }
    if (path.startsWith("file:/")) {
        return path.replace(/^file:\//, "/");
    }
}

type KVDB = MMKV & {
    getObject: <T = any>(key: string) => T | undefined;
    setObject: (key: string, value: any, tt: number)=> void;
}

function setObject(that: MMKV) {
    return (key: string, value: any, ttl: number) => {
        let obj = {
            [TTL_KEY]: Date.now() + ttl * 1000,
            v: value
        };
        that.set(key, JSON.stringify(obj));
    }
}


function getObject(that: MMKV) {
    return <T>(key: string) =>  {
        try {
            const obj = JSON.parse(that.getString(key)!) as {
                [TTL_KEY]: number;
                v: T
            };
            if (Date.now() - obj[TTL_KEY] > -1) {
                that.remove(key);
                return undefined;
            }
            return obj.v;
        } catch(e) {
            // that.remove(key);
        }
       
    }
}

let globalStorage: KVDB = null!;
export function getGlobalStorage() {
    if (!globalStorage) {
        // @ts-ignore
        globalStorage = createMMKV({
            id: `global`,
            path: fixPath(fs.cacheDirectory??''),
        });
        globalStorage.setObject = setObject(globalStorage);
        globalStorage!.getObject = getObject(globalStorage);
    }
    return globalStorage;
}

let caches: KVDB = null!;
export function getCaches() {
    if (!caches) {
        // @ts-ignore
        caches = createMMKV({
            id: `caches`,
            path: fixPath(fs.cacheDirectory??''),
        });
        caches.setObject = setObject(caches);
        caches!.getObject = getObject(caches);
    }
    return caches;
}

let apiCache: KVDB = null!;
export function getApiCache() {
    if (!apiCache) {
        // @ts-ignore
        apiCache = createMMKV({
            id: `api_cache`,
            path: fixPath(fs.cacheDirectory??''),
        });
        apiCache.setObject = setObject(apiCache);
        apiCache!.getObject = getObject(apiCache);
    }
    return apiCache;
}


setTimeout(()=> {

let lastClearTime = parseInt(globalStorage.getString("$__last_clear_time$_") || "0");
const clearTimeout = 86400 * 3 * 1000;
// 开启一直 15 分钏的定时器，用于清理缓存
setInterval(() => {
    let now = Date.now();
    if (now - lastClearTime < clearTimeout) {
        lastClearTime = now;
        caches.getAllKeys().forEach(key => {
            caches.getObject(key);
        });
        apiCache.getAllKeys().forEach(key => {
            apiCache.getObject(key);
        });
        globalStorage.getAllKeys().forEach(key => {
            globalStorage.getObject(key);
        });

        globalStorage.set("$__last_clear_time$_", now);
    }
}, 60 * 15 * 1000);
}, 3000);