
/* eslint global-require: 1 */
// @flow
import { app, BrowserWindow } from 'electron';
import electronDebug from 'electron-debug';
import installExtension, { REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } from 'electron-devtools-installer';
import devtron from 'devtron';
import sourceMapSupport from 'source-map-support';
import MenuBuilder from './utils/menu';
import SettingBuilder from './utils/setting';

let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  electronDebug();
}

const installExtensions = async () => {
  devtron.install();

  return Promise
    .all([
      installExtension(REACT_DEVELOPER_TOOLS),
      installExtension(REDUX_DEVTOOLS),
    ])
    .catch((error) => {
      console.log(error);
    });
};

/**
 * Add event listeners...
 */

app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('ready', async () => {
  if (process.env.NODE_ENV === 'development') {
    await installExtensions();
  }

  const settingBuilder = new SettingBuilder();
  const appSettings = await settingBuilder.loadAppSettings();

  const { width, height } = appSettings.windowSize;
  mainWindow = new BrowserWindow({
    show: false,
    minWidth: 1024,
    minHeight: 768,
    width,
    height,
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.on('ready-to-show', () => {
    mainWindow.show();
    mainWindow.focus();
  });

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

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();
});
