//
//  MP_DownloadManager.swift
//  MusicPlayer
//
//  Created by 忆海16 on 2024/5/14.
//

import Foundation
import Foundation
import Alamofire

class DownloadManager {
    
    static let shared = DownloadManager()
    
    private init() {}
    
    func downloadVideo(from url: URL, videoId: String, progressView: CircularProgressView, completion: @escaping (Result<URL, Error>) -> Void) {
        let destination: DownloadRequest.Destination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let downloadsURL = documentsURL.appendingPathComponent("Downloads")
            
            // 检查并创建 Downloads 文件夹
            if !FileManager.default.fileExists(atPath: downloadsURL.path) {
                do {
                    try FileManager.default.createDirectory(at: downloadsURL, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    completion(.failure(error))
                    return (downloadsURL, [.removePreviousFile, .createIntermediateDirectories])
                }
            }
            
            let fileURL = downloadsURL.appendingPathComponent("\(videoId).mp4")
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        AF.download(url, to: destination).downloadProgress { progress in
            progressView.setProgress(to: CGFloat(progress.fractionCompleted))
        }.response { response in
            if let error = response.error {
                completion(.failure(error))
            } else if let filePath = response.fileURL {
                completion(.success(filePath))
            }
        }
    }
}
