import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'window_listener.dart';

const kEventOnWindowShow = 'onWindowShow';
const kEventOnWindowHide = 'onWindowHide';

class WindowController {
  final _channel = const MethodChannel("app.flashlink/app");
  final ObserverList<WindowListener> _listeners =
      ObserverList<WindowListener>();

  WindowController() {
    _channel.setMethodCallHandler(_methodCallHandler);
  }

  Future<void> _methodCallHandler(MethodCall call) async {
    for (final WindowListener listener in _listeners) {
      switch (call.method) {
        case kEventOnWindowShow:
          listener.onWindowShow();
          break;
        case kEventOnWindowHide:
          listener.onWindowHide();
          break;
      }
    }
  }

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

  // 隐藏窗口
  Future<void> hideWindow() async {
    return _channel.invokeMethod('hideWindow');
  }

  // 切换窗口
  Future<void> toggleWindow() {
    return _channel.invokeMethod('toggleWindow');
  }

  // 退出程序
  Future<void> quitApplication() {
    return _channel.invokeMethod('destroyWindow');
  }

  bool get hasListeners {
    return _listeners.isNotEmpty;
  }

  void addListener(WindowListener listener) {
    _listeners.add(listener);
  }

  void removeListener(WindowListener listener) {
    _listeners.remove(listener);
  }
}
