//
//  FlutterMethodChannelManager.swift
//  Runner
//
//  Created by Destiny on 2025/5/8.
//

import Flutter
import UIKit

class FlutterMethodChannelManager: NSObject {
    
    // 单例模式
    static let shared = FlutterMethodChannelManager()
    
    // 方法通道
    var keyboardChannel: FlutterMethodChannel?
    
    // 私有初始化方法
    private override init() {
        super.init()
    }

    // 设置方法通道
    func setupMethodChannels(controller: FlutterViewController) {
        // 创建键盘相关的方法通道
        keyboardChannel = FlutterMethodChannel(
            name: "keyboard_ios",
            binaryMessenger: controller.binaryMessenger)
        
        // 设置方法调用处理器
        keyboardChannel?.setMethodCallHandler { [weak self] (call, result) in
            guard let self = self else { return }
            
            switch call.method {
            case "saveAuthToken":
                if let args = call.arguments as? [String: Any],
                   let token = args["token"] as? String {
                    KeyboardSharedDataManager.shared.saveToken(token)
                    result(true)
                } else {
                    result(FlutterError(code: "INVALID_ARGUMENTS", message: "无效的参数", details: nil))
                }
            case "clearAuthToken":
                KeyboardSharedDataManager.shared.clearAuthToken()
                result(true)
            case "saveIDFV":
                if let args = call.arguments as? [String: Any],
                   let idfv = args["idfv"] as? String {
                    KeyboardSharedDataManager.shared.saveInitIDFV(idfv)
                    result(true)
                } else {
                    result(FlutterError(code: "INVALID_ARGUMENTS", message: "无效的参数", details: nil))
                }
            case "saveIDFA":
                if let args = call.arguments as? [String: Any],
                   let idfa = args["idfa"] as? String {
                    KeyboardSharedDataManager.shared.saveInitIDFA(idfa)
                    result(true)
                } else {
                    result(FlutterError(code: "INVALID_ARGUMENTS", message: "无效的参数", details: nil))
                }
            case "isKeyboardAdded":
                let isAdd = self.isKeyboardEnabled()
                result(isAdd)
            case "isDefaultKeyboard":
                let isDefault = self.isCustomKeybroad()
                result(isDefault)
            case "openKeyboardGuide":
                KeyboardSharedDataManager.shared.saveIsShowGuide()
                result(true)
            default:
                result(FlutterMethodNotImplemented)
            }
        }
    }
    
    // 是否添加键盘
    func isKeyboardEnabled() -> Bool {
        
        // 获取系统中已安装的键盘列表
        let keyboards = UserDefaults.standard.dictionaryRepresentation()
            .filter { $0.key.contains("Keyboard") }
        if let keyboardList = keyboards["AppleKeyboards"] as? [String] {
            
            let keyboardBundleId = "com.qihuan.zhuiaijianpan.AiKeyboard"
            let isAdded = keyboardList.contains(keyboardBundleId)
            return isAdded
        }
        return false
    }
    
    // 是否为默认键盘
    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
    }
}
