//
//  CLXFileManager.swift
//  Runner
//
//  Created by MrQi on 2023/10/20.
//

import Flutter
import UIKit
import SVProgressHUD

@objcMembers
public class CLXFileManagePlugin: NSObject {
    public static func register(message: FlutterBinaryMessenger) {
        let channel = FlutterMethodChannel(name: "clx_file_manage", binaryMessenger: message)
        channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
            if call.method == "downloads" {
                guard let filePath = call.arguments as? String else {
                    result("下载失败，URL错误")
                    return
                }
                downloadFile(filePath: filePath, result: result)
            } else if call.method == "copy_to_public" {
                guard let agrs = call.arguments as? [String: String?] else {
                    result("文件打开失败，URL错误")
                    return
                }
                guard let filePath = agrs["private_path"] as? String else {
                    result("文件打开失败，URL错误")
                    return
                }
                guard let openUrl = URL(string: filePath) else {
                    result("下载失败，URL错误：" + filePath)
                    return }
                starShareFile(filePath: openUrl)
            }
        }
    }
    
    static func downloadFile(filePath: String, result: @escaping (_ res: Any) -> Void) {
        guard let requestUrl = URL(string: filePath) else {
            result("下载失败，URL错误：" + filePath)
            return }
        SVProgressHUD.dismiss()
        SVProgressHUD.show()
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = session.downloadTask(with: URLRequest(url: requestUrl)) { (url, response, error) in
            SVProgressHUD.dismiss()
            if (error != nil) {
                result("下载失败，Error: " + error.debugDescription)
            } else {
                guard let url = url else {
                    result("下载失败，请清理缓存后重试！")
                    return }
                
                let fileName = "/\(Date().timeIntervalSince1970)\(requestUrl.lastPathComponent)"
                guard let savePath = fileSavePath(String(fileName)) else {
                    return }
                var saveUrl: URL?
                if #available(iOS 16.0, *) {
                    saveUrl = URL.init(filePath: savePath)
                } else {
                    saveUrl = URL(fileURLWithPath: savePath)
                }
                guard let saveUrl = saveUrl else {
                    result("保存失败，请清理缓存后重试！")
                    return }
                try? FileManager.default.moveItem(at: url, to: saveUrl)
                starShareFile(filePath: saveUrl)
            }
        }
        task.resume()
    }
    
    /// 获取文件存储沙盒路径
    static func fileSavePath(_ fileName: String) -> String? {
        return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first?.appending(fileName)
    }
    
    /// 检测文件是否已经存在
    static func fileExists(_ fileName: String) -> Bool {
        guard let path = fileSavePath(fileName) else { return false }
        return FileManager.default.fileExists(atPath: path)
    }
    
    /// 写入本地文件
    static func writeFile(data: Data?,fileName: String) -> String? {
        guard let data = data else { return nil }
        guard let path = fileSavePath(fileName) else { return nil }
        if FileManager.default.createFile(atPath: path, contents: data) {
            return path
        } else {
            return nil
        }
    }
    
    /// 弹出文件拷贝
    static func starShareFile(filePath: URL) {
        if Thread.current.isMainThread {
            let ctrl = UIActivityViewController.init(activityItems: [filePath], applicationActivities: nil)
            if ((UIApplication.shared.windows.first?.rootViewController?.presentedViewController) != nil) {
                UIApplication.shared.windows.first?.rootViewController?.presentedViewController?.present(ctrl, animated: true)
            } else {
                UIApplication.shared.windows.first?.rootViewController?.present(ctrl, animated: true)
            }
        } else {
            DispatchQueue.main.async {
                let ctrl = UIActivityViewController.init(activityItems: [filePath], applicationActivities: nil)
                if ((UIApplication.shared.windows.first?.rootViewController?.presentedViewController) != nil) {
                    UIApplication.shared.windows.first?.rootViewController?.presentedViewController?.present(ctrl, animated: true)
                } else {
                    UIApplication.shared.windows.first?.rootViewController?.present(ctrl, animated: true)
                }
            }
        }
    }
}
