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

import Flutter
import UIKit

class FlutterMethodChannelManager: NSObject {
    
    // 单例模式
    static let shared = FlutterMethodChannelManager()
    
    // 方法通道
    private 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))
                }
            default:
                result(FlutterMethodNotImplemented)
            }
        }
    }
    
    // 保存认证Token到App Group共享存储
    private func saveAuthToken(_ token: String) {
        if let userDefaults = UserDefaults(suiteName: "group.com.yourcompany.aikeyboard") {
            userDefaults.set(token, forKey: "auth_token")
            userDefaults.synchronize()
            print("认证Token已保存到共享存储")
        } else {
            print("无法访问App Group共享存储")
        }
    }
    
    // 从App Group共享存储获取认证Token
    private func getAuthToken() -> String? {
        let userDefaults = UserDefaults(suiteName: "group.com.yourcompany.aikeyboard")
        return userDefaults?.string(forKey: "auth_token")
    }
}
