//
//  PQDownloadFileManager.swift
//  PQSpeed
//
//  Created by SanW on 2020/12/9.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import UIKit
import BFCommonKit

class PQDownloadFileManager: NSObject {
    /// 创建文件
    /// - Parameter url: 原地址
    /// - Returns: <#description#>
    class func createDownloadFilePath(url: String, fileExtensionType: FileExtensionType?) -> String {
        let fileManager = FileManager.default
        let filePath = downloadFileLocalPath(url: url, fileExtensionType: fileExtensionType)
        if !fileManager.fileExists(atPath: filePath) {
            let isFinished = fileManager.createFile(atPath: filePath, contents: nil, attributes: nil)
            BFLog(message: "生成本地地址：\(url),localPath = \(filePath)，isFinished：\(isFinished)")
        } else {
            BFLog(message: "已存在本地地址：\(url),localPath = \(filePath)")
        }
        return filePath
    }

    /// 获取文件本地存储地址
    /// - Parameter url: 原地址
    /// - Returns: <#description#>
    class func downloadFileLocalPath(url: String, fileExtensionType: FileExtensionType?) -> String {
        if url.hasPrefix(downloadDirectory) {
            return url
        }
        let type: String = fileExtensionType?.rawValue ?? url.pathExtension
        BFLog(message: "localPath : \(downloadDirectory + url.md5 + (type.count > 0 ? ".\(type)" : ""))")
        return downloadDirectory + url.md5 + (type.count > 0 ? ".\(type)" : "")
    }

    /// 获取已缓存大小
    /// - Parameter url: <#url description#>
    /// - Returns: <#description#>
    class func downloadFileLength(url: String, fileExtensionType: FileExtensionType?) -> Int64 {
        let fileManager = FileManager.default
        let filePath = downloadFileLocalPath(url: url, fileExtensionType: fileExtensionType)
        if fileManager.fileExists(atPath: filePath) {
            let att = try? fileManager.attributesOfItem(atPath: filePath)
            return Int64((att?[FileAttributeKey.size] as? UInt64) ?? 0)
        }
        return 0
    }

    /// 移除已下载文件
    /// - Parameter url: <#url description#>
    /// - Returns: <#description#>
    class func removeDownloadFile(url: String, fileExtensionType: FileExtensionType?) {
        let fileManager = FileManager.default
        var path = url
        if !path.hasPrefix(downloadDirectory) {
            path = downloadFileLocalPath(url: url, fileExtensionType: fileExtensionType)
        }
        if fileManager.fileExists(atPath: path) {
            BFLog(message: "删除本地文件 == \(path)")
            try? fileManager.removeItem(atPath: path)
        }
    }

    /// 获取下载的总数量
    /// - Returns: <#description#>
    class func downloadTotalFile() -> [String]? {
        let fileManager = FileManager.default
        let subpaths = fileManager.subpaths(atPath: downloadDirectory)
        BFLog(message: "已下载的总文件 == \(subpaths ?? [])")
        return subpaths
    }
}
