import UIKit
import Flutter
import WebKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    


    let flutterChannelName = "o2oa.net/flutter_inner"
    
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
     
          // 插件内部调用
          let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
          let batteryChannel = FlutterMethodChannel(name: flutterChannelName,
                                                    binaryMessenger: controller.binaryMessenger)
          batteryChannel.setMethodCallHandler({
            (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
              self.handle(call: call, result: result, controller: controller)
          })
          //
          GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    
    
    private func handle(call: FlutterMethodCall, result: @escaping FlutterResult, controller : FlutterViewController ) {
        // 参数
        let args = call.arguments as? [String:Any]
        switch call.method {
        case "openFile": // 打开文档
            print("打开文件的方法 ios！")
            if let filePath = (args?["filePath"] as? String) {
                let shareBtnShow = (args?["shareBtnShow"] as? Bool) ?? true
                let doneTitle = (args?["doneTitle"] as? String) ?? "关闭"
                let openFile = OpenFilePlugin()
                openFile.handleMethodCallOpenFile(filePath: filePath, result: result, shareBtnShow: shareBtnShow, doneTitle: doneTitle)
            } else {
                result("没有传入filePath")
            }
            break
        case "clearCache":
            print("清除缓存 ios！")
            self.clearCache(result: result)
            break
        case "checkRoot":
            print("越狱检查 ios！")
            self.checkRoot(result: result)
            break
        case "saveToAlbum":
            print("保存到相册")
            if let filePath = (args?["filePath"] as? String), !filePath.isEmpty {
                self.saveToAlbum(filePath: filePath, result: result)
            } else {
                result("没有传入filePath")
            }
            break
        default :
            result(FlutterMethodNotImplemented)
            break
        }
    }
    
    private func saveToAlbum(filePath: String, result: @escaping FlutterResult) {
        let currentURL = NSURL(fileURLWithPath: filePath)
        if let url = currentURL.path {
            UIImageWriteToSavedPhotosAlbum(UIImage(contentsOfFile: url)!, self, #selector(self.saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
        }
        result(true)
    }
    
    @objc func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) {
        if let e = error {
            print(e.localizedDescription)
        } else {
            print("保存图片到相册成功！")
        }
    }
    
    /// 越狱检查
    private func checkRoot(result: @escaping FlutterResult) {
        var checked = false
        #if !targetEnvironment(simulator)
            print("不是模拟器啦。。。。。")
            //越狱检查
            checked =  SecurityCheckManager.shared.isJailBroken()
        #endif
        result(checked)
    }
    
    
    let group = DispatchGroup()
    private func clearCache(result: @escaping FlutterResult) {
        self.group.enter()
        DispatchQueue.main.async(group: self.group, execute: DispatchWorkItem(block: {
            let types = WKWebsiteDataStore.allWebsiteDataTypes()
            WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: Date(timeIntervalSince1970: 0), completionHandler: {
                print("浏览器缓存清除")
                self.group.leave()
            })
        }))
        self.group.notify(queue: DispatchQueue.main) {
            result("success")
        }
    }
 
}
 
