'use strict';

const electron = require('electron');
var path = require('path')
const app = electron.app;  // Module to control application life.
const BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
const ipcMain = electron.ipcMain;
const { localStorage } = require('electron-browser-storage');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var win = null;

if (process.platform != "linux") {
  app.commandLine.appendSwitch("disable-impl-side-painting", "true")
  app.commandLine.appendSwitch("force-gpu-rasterization", "true")
  app.commandLine.appendSwitch("allow-file-access-from-files", "true")
  app.commandLine.appendSwitch("ignore-gpu-blacklist", "true")
  app.commandLine.appendSwitch("enable-gpu-rasterization", "true")
  app.commandLine.appendSwitch("enable-zero-copy", "true")
  app.commandLine.appendSwitch("disable-software-rasterizer", "true")
  app.commandLine.appendSwitch("disable-renderer-backgrounding")
  app.commandLine.appendSwitch("num-raster-threads", (require("os").cpus().length).toString())

  app.commandLine.appendSwitch('in-process-gpu') // overlay??
  app.commandLine.appendSwitch('disable-transparency') // overlay??
}

// fixes for electron 2.0.2 / chromium 61: https://github.com/electron/electron/issues/13088
app.commandLine.appendSwitch("enable-color-correct-rendering", "false")
app.commandLine.appendSwitch("enable-draw-occlusion", "true")
app.commandLine.appendSwitch("force-color-profile", "sRGB")

// This method will be called when Electron has finished initialization and is ready to
// create browser windows.
app.on('ready', async function() {

  // Create the browser window.
  win = new BrowserWindow({
    title: "Curious Expedition",
    width: 1280, 
    height: 720,
    useContentSize: true,
    icon: path.join(__dirname, 'img/tce-icon.png')
  });

  var isIOSetting = await localStorage.getItem("isIO");
  var isIO = isIOSetting == "true";

  if (isIO)
  {
    win.loadURL('file://' + __dirname + '/play-electron-io.html');
  }
  else
  {
    win.loadURL('file://' + __dirname + '/play-electron.html');
  }

  // Open the DevTools.
  if (process.argv.includes('-console'))
  {
    win.webContents.openDevTools();
  }
  
  // Emitted before the window is closed.
  var hasPreventedQuit = false;
  win.on('close', function(event) {
    if (!hasPreventedQuit)
    {
      hasPreventedQuit = true;
      event.preventDefault()
      win.webContents.executeJavaScript("HandleElectronClose();");
    }
  });

  // Emitted when the window is closed.
  win.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null;
    
    if (process.platform != 'darwin') {
      app.quit();
    }
  });
});

