import Cocoa
import FlutterMacOS
import window_manager

import UserNotifications
@main
class AppDelegate: FlutterAppDelegate {
  override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    // 不终止应用，而是隐藏窗口
    return false
  }
  override func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Request notification authorization
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { granted, error in
            if let error = error {
                print("Error requesting notification authorization: \(error)")
            }
        }
    }

  // 处理应用重新打开事件
  override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
    if !flag {
      for window in NSApp.windows {
        window.makeKeyAndOrderFront(nil)
        NSApp.activate(ignoringOtherApps: true)
      }
    }
    return true
  }

  // 处理应用终止事件（包括强制退出）
  override func applicationWillTerminate(_ notification: Notification) {
    // 在这里可以执行清理操作
    // 例如：保存状态、关闭连接等
    print("应用程序即将终止")

    // 通知 Flutter 端应用即将终止
    if let controller = NSApp.windows.first?.contentViewController as? FlutterViewController {
      let channel = FlutterMethodChannel(name: "hifast_vpn/terminate", binaryMessenger: controller.engine.binaryMessenger)
      channel.invokeMethod("onTerminate", arguments: nil)
    }
  }

  // 支持安全的状态恢复
  override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
    return true
  }

  // // window manager restore from dock: https://leanflutter.dev/blog/click-dock-icon-to-restore-after-closing-the-window
  // override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
  //     if !flag {
  //         for window in NSApp.windows {
  //             if !window.isVisible {
  //                 window.setIsVisible(true)
  //             }
  //             window.makeKeyAndOrderFront(self)
  //             NSApp.activate(ignoringOtherApps: true)
  //         }
  //     }
  //     return true
  // }
}
