//
//  String+Cache.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/25.
//

import UIKit

extension String {
    
    /// 是否存在
    @discardableResult
    func fileExists() -> Bool {
        let su = FileManager.default.fileExists(atPath: self)
        if !su {
            FileManager.default.createFile(atPath: self, contents: nil)
        }
        return su
    }
    
    /// 获取文档路径
    func documentURL() -> URL {
        let document = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        return document.appendingPathComponent(self)
    }
    
    func document() -> String {
        return (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? "").appending("/\(self)")
    }
    
    func deleteFiles(_ files:[String]) -> Void {
        for name in files {
            do {
                try FileManager.default.removeItem(atPath: name)
            }catch{
                Print("删除出错了")
            }
        }
    }
    
}


extension URL {
    // 是否是文件夹
    @discardableResult
    func isDirect(_ create:Bool = true) -> Bool {
        var isDirectory: ObjCBool = false
        let exists = FileManager.default.fileExists(atPath: self.absoluteString, isDirectory: &isDirectory)
        if exists && isDirectory.boolValue { }else{
            if create {
                do {
                    try FileManager.default.createDirectory(at: self, withIntermediateDirectories: false, attributes: nil)
                }catch{
                }
            }
        }
        return exists && isDirectory.boolValue
    }
}
