//
//  CacheTool.swift
//  E-Wow
//
//  Created by lym on 2021/1/5.
//

import Cache
import Foundation

// MARK: - cache keys

enum CacheKey: String {
    case user
    case token
    case pushToken
    case ImAppkeyInfo
    case keyword
    case homeEnterBackgroundTime
    case boolIdfaSubmmited

    // MARK: Flag
    case meetGuideSeen
    
    // MARK: Setting
    
    
    // MARK: Config
    case userAppLanguage
    case chatRedBadgeConfig
    
    // MARK: Chat & Friends
    case friendsHeartBeatShowedOnce
    
    // MARK: Test
    
    case testRecordAIId
}

// MARK: - config

let diskConfig = DiskConfig(name: AppConst.bundleId)

let dataStorage = try! Storage<String, Data>(
    diskConfig: diskConfig,
    memoryConfig: MemoryConfig(),
    transformer: TransformerFactory.forData()
)

// MARK: - AppCache

class AppCache {
    // Add objects to the cache
    class func cache<T: Codable>(key: String, value: T) {
        let storage = dataStorage.transformCodable(ofType: T.self)
        do {
            try storage.setObject(value, forKey: key)
            dlog("✅ 缓存成功：key = \(key), value = \(value)")
        } catch {
            dlog("❌ 缓存错误：\(error)")
        }
    }

    // Fetch object from the cache
    class func fetchCache<T: Codable>(key: String, type: T.Type) -> T? {
        do {
            let storage = dataStorage.transformCodable(ofType: type)
            let value = try storage.object(forKey: key)
            return value
        } catch {
            dlog("❌ 获取缓存失败：key = \(key), error = \(error)")
            return nil
        }
    }

    // Remove object from the cache
    class func removeCache(key: String) {
        do {
            try dataStorage.removeObject(forKey: key)
        } catch {
            dlog("❌ remove cache error = \(error)")
        }
    }

    // Clear cache
    class func clearCache() {
        do {
            try dataStorage.removeAll()
        } catch {
            dlog("❌ clear cache erro")
        }
    }
}

extension Array: Encodable, Decodable {}
