//
//  OpenFilePlugin.swift
//  Runner
//
//  Created by FancyLou on 2023/5/23.
//

import UIKit
import Flutter
import QuickLook


class OpenFilePlugin {
    //预览文件
    private lazy var previewVC: FilePreviewController = {
        return FilePreviewController()
    }()
    
    //
    func handleMethodCallOpenFile(filePath: String, result: @escaping FlutterResult, shareBtnShow: Bool = true, doneTitle: String = "关闭") {
        guard let root = (UIApplication.shared.delegate as? AppDelegate)?.window.rootViewController else {
            result("fail")
            return
        }
        let currentURL = NSURL(fileURLWithPath: filePath)
        if QLPreviewController.canPreview(currentURL) {
            self.previewVC.currentFileURLS.removeAll()
            self.previewVC.currentFileURLS.append(currentURL)
            self.previewVC.reloadData()
            if !shareBtnShow { // 为了隐藏分享按钮，需要新创建一个 UIViewController
                let previewNoActionVC = FilePreviewNoActionbarViewController()
                previewNoActionVC.addChild(self.previewVC)
                self.previewVC.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                previewNoActionVC.view.addSubview(self.previewVC.view)
                previewNoActionVC.doneTitle = doneTitle
                previewNoActionVC.modalPresentationStyle = .fullScreen
                root.show(previewNoActionVC , sender: nil)
            } else {
                root.show(self.previewVC , sender: nil)
            }
            result("success")
        } else {
            //self.showError(title: "当前文件类型不支持预览！")
            result("fail")
        }
         
    }
    
    
    
}
