//
//  TSFileManagerTool.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/26.
//

class TSFileManagerTool {
    
    /// 获取 Video 下载后保存的的文件件路径
    static var saveDownVideoPathURL:URL = {
        let saveVideoPathURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("livePhoto").appendingPathComponent("saveVideo")
        return saveVideoPathURL
    }()
    
    /// 获取 Video 临时编辑的文件件路径
    static var editLiveVideoPathURL:URL = {
        let editVideoPathURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("livePhoto").appendingPathComponent("editVideo")
        return editVideoPathURL
    }()
    
    /// 获取 Video 编辑后保存的的文件件路径
    static var saveLiveVideoPathURL:URL = {
        let saveVideoPathURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("livePhoto").appendingPathComponent("saveVideo")
        return saveVideoPathURL
    }()
    

    /// 获取沙盒 Documents 目录路径
    static var documentsDirectory: URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    }

    /// 获取沙盒 Cache 目录路径
    static var cacheDirectory: URL {
        return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
    }

    /// 获取沙盒 Temporary 目录路径
    static var temporaryDirectory: URL {
        return FileManager.default.temporaryDirectory
    }

    static func copyFileWithOverwrite(from sourceURL: URL, to targetURL: URL) {
        let fileManager = FileManager.default
        do {
            removeItem(from: targetURL)
            checkFolderAndCreate(from: targetURL)
            try fileManager.copyItem(at: sourceURL, to: targetURL)
            debugPrint("文件复制成功！")
        } catch {
            debugPrint("文件复制失败: \(error.localizedDescription)")
        }
    }
    
    static func removeItem(from sourceURL: URL) {
        let fileManager = FileManager.default
        do {
            // 如果目标路径存在同名文件，先删除旧文件
            if fileManager.fileExists(atPath: sourceURL.path) {
                try fileManager.removeItem(at: sourceURL)
            }
            debugPrint("文件删除成功！")
        } catch {
            debugPrint("文件删除失败: \(error.localizedDescription)")
        }
    }
    
    /// 移动文件的方法（自动创建目标文件夹）
    /// - Parameters:
    ///   - sourceURL: 文件的源 URL
    ///   - destinationURL: 目标 URL
    /// - Throws: 如果移动失败，会抛出错误
    static func moveFile(from sourceURL: URL, to destinationURL: URL) {
        let fileManager = FileManager.default
        
        // 检查源文件是否存在
        guard fileManager.fileExists(atPath: sourceURL.path) else {
            let error = NSError(domain: "FileMoveError", code: 404, userInfo: [NSLocalizedDescriptionKey: "源文件不存在"])
            debugPrint(error)
            return
        }
        
        // 获取目标文件夹的路径
        let destinationDirectory = destinationURL.deletingLastPathComponent()
        do {
            // 如果目标文件夹不存在，创建文件夹
            if !fileManager.fileExists(atPath: destinationDirectory.path) {
                try fileManager.createDirectory(at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
            }
            
            // 检查目标路径是否已经存在文件
            if fileManager.fileExists(atPath: destinationURL.path) {
                // 如果需要覆盖，可以选择先删除目标文件
                try fileManager.removeItem(at: destinationURL)
            }
            
            // 尝试移动文件
            try fileManager.moveItem(at: sourceURL, to: destinationURL)
        } catch {
            debugPrint("尝试移动文件失败: \(error.localizedDescription)")
        }
    }
    
    static func getFileName(from url: URL, includeExtension: Bool = true) -> String {
        if includeExtension {
            return url.lastPathComponent
        } else {
            return url.deletingPathExtension().lastPathComponent
        }
    }
    
    static func checkFolderAndCreate(from destinationURL: URL){
        let fileManager = FileManager.default
        let destinationDirectory = destinationURL.deletingLastPathComponent()
        // 如果目标文件夹不存在，创建文件夹
        if !fileManager.fileExists(atPath: destinationDirectory.path) {
            do {
                try fileManager.createDirectory(at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
            } catch {
                debugPrint("尝试创建文件夹失败: \(error.localizedDescription)")
            }
        }
    }

    // MARK: - 文件操作方法

    /// 检查文件或文件夹是否存在
    static func fileExists(at url: URL) -> Bool {
        return FileManager.default.fileExists(atPath: url.path)
    }

    /// 创建文件夹
    static func createDirectory(at url: URL) throws {
        if !fileExists(at: url) {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    //获取缓存目录下文件夹路径
    static func getCacheSubPath(at url: URL) ->String? {
        let array = url.path.components(separatedBy:"/Caches/")
        let cashFilePath = array.last
        return cashFilePath
    }
    
}

extension String {
    var fillCachePath:String{
        return TSFileManagerTool.cacheDirectory.appendingPathComponent(self).path
    }
    
    var fillCacheURL:URL{
        return TSFileManagerTool.cacheDirectory.appendingPathComponent(self)
    }
}
