import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      GeneratedPluginRegistrant.register(with: self)
      
      let controller = window?.rootViewController as! FlutterViewController
      FlutterMethodChannelManager.shared.setupMethodChannels(controller: controller)
      
      // 创建事件通道
      let keyboardEventChannel = FlutterEventChannel(name: "keyboard_ios_events",
                                                        binaryMessenger: controller.binaryMessenger)
      // 设置事件处理器
      let keyboardStreamHandler = KeyboardStreamHandler()
      keyboardEventChannel.setStreamHandler(keyboardStreamHandler)
      // 开始监听键盘切换
      startMonitoringKeyboardChanges()
      
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
    override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        
        let path = url.path
        if let channel = FlutterMethodChannelManager.shared.keyboardChannel {
            if path == "/login" {
                channel.invokeMethod("navigateToLogin", arguments: nil)
            } else if path == "/member" {
                channel.invokeMethod("navigateToMember", arguments: nil)
            } else if path == "/character/market" {
                channel.invokeMethod("navigateToCharacterMarket", arguments: nil)
            } else if path == "/intimacy" {
                channel.invokeMethod("navigateToIntimacy", arguments: nil)
            } else if path == "/character/custom" {
                channel.invokeMethod("navigateToCustomCharacter", arguments: nil)
            }
        }
        
        return true
    }
    
    func startMonitoringKeyboardChanges() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidChange), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
    }

    @objc func keyboardDidChange() {
        // 收到通知后延迟检测
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
            if let isCustom = self?.isCustomKeybroad() {
                // 发送通知
                NotificationCenter.default.post(name: NSNotification.Name("KeyboardDidChange"), object: nil, userInfo: ["isCustomKeyboard": isCustom])
            }
        }
    }
    
    func isCustomKeybroad() -> Bool {
        
        let currentKeyboardName = (((UITextInputMode.activeInputModes as NSArray).filtered(using: NSPredicate(format: "isDisplayed = YES"))).last as? NSObject)?.value(forKey: "extendedDisplayName") as? String
        
        let infoDictionary = Bundle.main.infoDictionary!
        let appDisplayName = infoDictionary["CFBundleDisplayName"] as? String
        
        return currentKeyboardName == appDisplayName
    }
}


// 事件流处理器
class KeyboardStreamHandler: NSObject, FlutterStreamHandler {
    private var eventSink: FlutterEventSink?

    override init() {
        super.init()
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidChange(_:)), name: NSNotification.Name("KeyboardDidChange"), object: nil)
    }

    @objc func keyboardDidChange(_ notification: Notification) {
        if let userInfo = notification.userInfo,
           let isCustomKeyboard = userInfo["isCustomKeyboard"] as? Bool,
           let eventSink = eventSink {
            // 发送事件到Flutter
            eventSink(isCustomKeyboard)
        }
    }

    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        return nil
    }

    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        eventSink = nil
        return nil
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
