import 'dart:async';
import 'dart:io';

import 'menu_base/menu_base.dart';
import 'tray_controller.dart';
import 'tray_listener.dart';
import 'window_controller.dart';
import 'window_listener.dart';

class WindowService implements WindowListener, TrayListener {
  final _trayController = TrayController();
  final _windowController = WindowController();

  void Function(MenuItem menu)? _onMenuItemClick;

  void initialize() {
    // 监听系统托盘和窗口事件
    _trayController.addListener(this);
    _windowController.addListener(this);
  }

  void dispose() {
    // 取消监听
    _trayController.removeListener(this);
    _windowController.removeListener(this);
  }

  void terminate() async {
    await resetSystemTray();
    exit(0);
  }

  // 激活窗口
  Future<void> activeWindow() {
    return _windowController.activeWindow();
  }

  // 退出程序
  Future<void> quitApplication() {
    return _windowController.quitApplication();
  }

  // 设置托盘菜单
  Future<void> setSystemTrayMenu(
    Menu trayMenu,
    void Function(MenuItem menuItem) onMenuItemClick,
  ) {
    _onMenuItemClick = onMenuItemClick;
    return _trayController.setContextMenu(trayMenu);
  }

  // 设置托盘图标
  Future<void> setSystemTrayIcon(
    bool isConnected,
    bool isDark,
    String tooltip,
  ) {
    return _trayController.setSystemTray(isConnected, isDark, tooltip: tooltip);
  }

  // 销毁托盘图标
  Future<void> resetSystemTray() {
    return _trayController.resetSystemTray();
  }

  @override
  void onTrayMenuItemClick(MenuItem menuItem) {
    if (_onMenuItemClick != null) {
      _onMenuItemClick!(menuItem);
    }
  }

  @override
  void onTrayIconLButtonUp() {
    _windowController.toggleWindow();
  }

  @override
  void onTrayIconRButtonUp() {
    _trayController.popUpContextMenu();
  }

  @override
  void onTrayIconLButtonDown() {
    // 无响应
  }

  @override
  void onTrayIconRButtonDown() {
    // 无响应
  }

  @override
  void onWindowHide() {
    // 无响应
  }

  @override
  void onWindowShow() {
    // 无响应
  }
}
