//
//  ExampleIniter.swift
//  TSLiveWallpaper
//
//  Created by nkl on 2025/2/6.
//

import Foundation
import TSVideoKit

class ExampleIniter {
    static let `default` = ExampleIniter()

    private func uniqueFileURL(at directory: URL, originalURL: URL) -> URL {
        let fileManager = FileManager.default

        // 检查目录是否存在，如果不存在则创建目录
        if !fileManager.fileExists(atPath: directory.path) {
            do {
                try fileManager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
            } catch {
                // 这里可以选择抛出错误或处理错误
            }
        }

        let originalFilename = originalURL.deletingPathExtension().lastPathComponent
        let fileExtension = originalURL.pathExtension
        var uniqueURL = directory.appendingPathComponent(originalFilename).appendingPathExtension(fileExtension)

        var counter = 1
        while fileManager.fileExists(atPath: uniqueURL.path) {
            uniqueURL = directory.appendingPathComponent("\(originalFilename)-\(counter)").appendingPathExtension(fileExtension)
            counter += 1
        }

        return uniqueURL
    }

    func copyFileToUrl(url: URL) {
        let fileId = UUID().uuidString
        let path = TSVideoOperator.shared.configuration.fileDir.appendingPathComponent(fileId)
        let destinationURL = uniqueFileURL(at: path, originalURL: url)
        do {
            try FileManager.default.copyItem(at: url, to: destinationURL)
            Task {
                await self.importVideo(videoId: fileId, from: destinationURL)
            }

        } catch {
            print(error.localizedDescription)
        }
    }

    private func importVideo(videoId: String, from url: URL) async {
        let asset = AVAsset(url: url)
        let image = await asset.generateThumbnail()

        await MainActor.run {
            let title = url.lastPathComponent
            let pathExt = url.pathExtension.lowercased()
            let vPath = videoId + "/" + title

            let audios = ["mp3", "wav", "m4a"]
            var isRing: Bool = false
            if audios.contains(pathExt) {
                isRing = true
            }
            let imageData = image?.jpegData(compressionQuality: 0.8)
            let defaultData = UIImage(named: "ic_default")?.jpegData(compressionQuality: 0.8)
            let finalData = imageData ?? defaultData
            TSVideoOperator.shared.dataManager.createVideo(videoId: videoId, videoUrl: nil, audioStream: nil, videoStream: nil, videoTitle: title, artist: "UnKnown".localized(), artwork: finalData, online: false, customTag: isRing, status: .cached, vPath: vPath) { _ in
                NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
            }
        }
    }
}
