/**
 * Applies attributes based on the app/window.
 * @module Window
 * @memberof Builtin.Attributes.Misc
 */

import { IpcEvents } from '@vizality/constants';
import { ipcRenderer } from 'electron';

export const labels = [ 'Misc', 'Window' ];

export default () => {
  const root = document.documentElement;

  const setMaximized = () => root.setAttribute('vz-window', 'maximized');
  const setRestored = () => root.setAttribute('vz-window', 'restored');

  /**
   * Trigger the IPC event initially to set the attributes.
   */
  ipcRenderer.invoke(IpcEvents.VIZALITY_WINDOW_IS_MAXIMIZED).then(isMaximized => {
    if (isMaximized) {
      setMaximized();
    } else {
      setRestored();
    }
  });

  /**
   * Add listeners for when the window is maximized and restored.
   */
  ipcRenderer.on(IpcEvents.VIZALITY_WINDOW_MAXIMIZE, setMaximized);
  ipcRenderer.on(IpcEvents.VIZALITY_WINDOW_UNMAXIMIZE, setRestored);

  /**
   * Remove listeners on unload.
   */
  return () => {
    ipcRenderer.removeListener(IpcEvents.VIZALITY_WINDOW_UNMAXIMIZE, setRestored);
    ipcRenderer.removeListener(IpcEvents.VIZALITY_WINDOW_UNMAXIMIZE, setRestored);
  };
};
