import { BrowserWindow } from 'electron';
import os from 'os';
import { injectable } from 'inversify';
import { IAppWindow } from './i-app-window';
import BrowserWindowConstructorOptions = Electron.BrowserWindowConstructorOptions;

let defaultOptions = {
  width: 1600,
  height: 900,
  webPreferences: {
    nodeIntegration: false,
  },
};

switch (os.platform()) {
  case 'win32':
    defaultOptions = {
      ...defaultOptions,
      ...{
        icon: 'resources/icon.ico',
      },
    };
    break;
  default:
    break;
}

@injectable()
export abstract class AppWindow implements IAppWindow {
  protected _window: BrowserWindow | null;

  protected constructor(options: BrowserWindowConstructorOptions = {}) {
    this.initialize(options);
  }

  public get window(): BrowserWindow {
    return this._window;
  }

  public open(): Promise<void> {
    if (this.isClosed()) {
      this.initialize();
    }

    return this._window.loadFile('frontend/index.html');
  }

  public isClosed(): boolean {
    return !this._window;
  }

  private initialize(options: BrowserWindowConstructorOptions = {}): void {
    this._window = new BrowserWindow({ ...defaultOptions, ...options });

    this._window.on('closed', () => {
      this._window = null;
    });
  }
}
