import { BrowserWindow } from 'electron';
import { WindowState } from '@ucap-webmessenger/native';
import { WindowStateChannel } from '@ucap-webmessenger/native-electron';
import { ElectronBrowserWindowChannel } from '@ucap-webmessenger/electron-core';

export function getWindowState(window: Electron.BrowserWindow): WindowState {
  if (window.isFullScreen()) {
    return WindowState.FullScreen;
  } else if (window.isMaximized()) {
    return WindowState.Maximized;
  } else if (window.isMinimized()) {
    return WindowState.Minimized;
  } else if (!window.isVisible()) {
    return WindowState.Hidden;
  } else {
    return WindowState.Normal;
  }
}

export function registerWindowStateChangedEvents(window: BrowserWindow) {
  window.on(ElectronBrowserWindowChannel.EnterFullScreen, () =>
    sendWindowStateEvent(window, WindowState.FullScreen)
  );

  window.on(ElectronBrowserWindowChannel.LeaveFullScreen, () =>
    sendWindowStateEvent(window, WindowState.Normal)
  );

  window.on(ElectronBrowserWindowChannel.Maximize, () =>
    sendWindowStateEvent(window, WindowState.Maximized)
  );
  window.on(ElectronBrowserWindowChannel.Minimize, () =>
    sendWindowStateEvent(window, WindowState.Minimized)
  );
  window.on(ElectronBrowserWindowChannel.Unmaximize, () =>
    sendWindowStateEvent(window, WindowState.Normal)
  );
  window.on(ElectronBrowserWindowChannel.Restore, () =>
    sendWindowStateEvent(window, WindowState.Normal)
  );
  window.on(ElectronBrowserWindowChannel.Hide, () =>
    sendWindowStateEvent(window, WindowState.Hidden)
  );
  window.on(ElectronBrowserWindowChannel.Show, () => {
    // because the app can be maximized before being closed - which will restore it
    // maximized on the next launch - this function should inspect the current state
    // rather than always assume it is a 'normal' launch
    sendWindowStateEvent(window, getWindowState(window));
  });
}

function sendWindowStateEvent(window: BrowserWindow, windowState: WindowState) {
  window.webContents.send(WindowStateChannel.Changed, windowState);
}
