//
//  SpeakCache.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/25.
//

import UIKit


enum CacheFileNamePath:String {
    case MessageCache = "MessageCache.data"
    case PracticeCache = "PracticeCache.data"
}

class SpeakCache: NSObject {
    
    static let cache = SpeakCache()
    
    private let dir = "SpeakCache"
    private let audio = "audio"
    private let headerName = "avatar.png"
    
    private override init() {
        dir.documentURL().isDirect(true)
        dir.documentURL().appendingPathComponent(audio).isDirect(true)
    }
    
    func delete() -> Void {
        let url = dir.documentURL()
        do {
            try FileManager.default.removeItem(at: url)
        }catch {}
    }
    
    /// 保存头像
    func Save(data:Data?) -> Void {
        if let d = data {
            let url = dir.documentURL().appendingPathComponent(headerName)
            do {
                try d.write(to: url)
            }catch{}
        }
    }
    
    /// 加载本地头像
    func loadHeader() -> UIImage {
        let url = dir.document() + "/\(headerName)"
        let icon = UIImage(contentsOfFile: url)
        return icon ?? UIImage(named: "img_touxiang")!
    }
    
    func SaveModel<T:Codable>(cache:T? , state:CacheFileNamePath , name:String) -> Void {
        let path = dir.documentURL().appendingPathComponent(state.rawValue + name)
        do {
            let data = try JSONEncoder().encode(cache)
            try data.write(to: path)
        }catch {}
    }
    
    func LoadMode<T:Codable>(state:CacheFileNamePath ,name:String) -> T? {
        let path = dir.documentURL().appendingPathComponent(state.rawValue + name)
        do{
            let dddd = try Data(contentsOf: path)
            let data = try JSONDecoder().decode(T.self, from: dddd)
            return data
        }catch{
            return nil
        }
    }
    
    @discardableResult
    func saveData(data:Data,fileName:String) -> URL {
        let path = dir.documentURL().appendingPathComponent(audio).appendingPathComponent(fileName)
        do{
            try data.write(to: path)
        }catch{ }
        return path
    }
    
    func loadData(fileName:String) -> Data? {
        let path = dir.documentURL().appendingPathComponent(audio).appendingPathComponent(fileName)
        do {
            let d = try Data(contentsOf: path)
            return d
        }catch {}
        return nil
    }
}
