'use strict';

const electron = require('electron');
const fs = require('fs');
const os = require('os');
const menuTemplate = require('./menu.js');
const autoUpdate = require('./auto-update.js');

// needed to fix notifications in win 10
// see https://github.com/electron/electron/issues/10864
electron.app.setAppUserModelId('org.dainst.field');

// Copy config file to appData if no config file exists in appData
const copyConfigFile = (destPath, appDataPath) => {

    if (!fs.existsSync(appDataPath)) fs.mkdirSync(appDataPath);

    if (!fs.existsSync(destPath)) {
        console.log('Create config.json at ' + destPath);
        fs.writeFileSync(destPath, JSON.stringify({ 'dbs': ['test'] }));
    }
};


global.setConfigDefaults = config => {

    if (!config.syncTarget) config.syncTarget = {};
    if (!config.remoteSites) config.remoteSites = [];
    if (config.isAutoUpdateActive === undefined) config.isAutoUpdateActive = true;
    if (os.type() === 'Linux') config.isAutoUpdateActive = false;

    return config;
};


// CONFIGURATION ---

let env = undefined;
if (process.argv && process.argv.length > 2) {
    env = process.argv[2];
}

if (env) { // is environment 'dev' (npm start) or 'test' (npm run e2e)
    global.configurationDirPath = 'config';
}

if (!env || env === 'test') {
    global.mode = 'production';
} else {
    global.mode = 'development';
}

const isInTestEnvironment = () => {

    return env && env.indexOf('test') !== -1;
};


if (!env || // is environment 'production' (packaged app)
    env.indexOf('dev') !== -1) { // is environment 'development' (npm start)

    global.appDataPath = electron.app.getPath('appData') + '/' + electron.app.getName();
    copyConfigFile(global.appDataPath + '/config.json', global.appDataPath);
    global.configPath = global.appDataPath + '/config.json';

    if (!env) { // is environment 'production' (packaged app)
        global.configurationDirPath = '../config';
    }

} else { // is environment 'test' (npm run e2e)

    global.configPath = 'config/config.test.json';
    global.appDataPath = 'test/test-temp';
}

console.log('Using config file: ' + global.configPath);
global.config = global.setConfigDefaults(
    JSON.parse(fs.readFileSync(global.configPath, 'utf-8'))
);


// -- CONFIGURATION

// OTHER GLOBALS --

global.switches = {
    prevent_reload: false,
    destroy_before_create: false,
    messages_timeout: 3500,
    suppress_map_load_for_test: false,
    provide_reset: false
};

if (isInTestEnvironment()) {
    global.switches.messages_timeout = undefined;
    global.switches.prevent_reload = true;
    global.switches.destroy_before_create = true;
    global.switches.suppress_map_load_for_test = true;
    global.switches.provide_reset = true;
}

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = true;


// -- OTHER GLOBALS

// 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.
let mainWindow;

const createWindow = () => {

    const screenWidth = electron.screen.getPrimaryDisplay().workAreaSize.width;
    const screenHeight = electron.screen.getPrimaryDisplay().workAreaSize.height;

    mainWindow = new electron.BrowserWindow({
        width: screenWidth >= 1680 ? 1680 : 1280,
        height: screenHeight >= 1050 ? 1050 : 800,
        minWidth: 1220, // to allow for displaying project names like 'mmmmmmmmmmmmmmmmmm'
        minHeight: 600,
        webPreferences: {
            nodeIntegration: true,
            webSecurity: !isInTestEnvironment()
        },
        titleBarStyle: 'hiddenInset'
    });

    const menu = electron.Menu.buildFromTemplate(menuTemplate);
    electron.Menu.setApplicationMenu(menu);

    // and load the index.html of the app.
    mainWindow.loadURL('file://' + __dirname + '/index.html');

    // Open the DevTools.
    // mainWindow.webContents.openDevTools();

    // Emitted when the window is closed.
    mainWindow.on('closed', () => {
        // 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.
        mainWindow = null;
    });

    return mainWindow;
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
electron.app.on('ready', () => {
    const mainWindow = createWindow();
    if (global.config.isAutoUpdateActive) autoUpdate.setUp(mainWindow);

    electron.ipcMain.on('settingsChanged', (event, settings) => {
        if (settings.isAutoUpdateActive) autoUpdate.setUp(mainWindow);
    });
});

electron.app.on('activate', () => {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow();
    }
});

// Quit when all windows are closed.
electron.app.on('window-all-closed', () => {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        electron.app.quit();
    }
});

@@ -1274,29 +1274,31 @@
 !env
- %7C%7C env === 'test') %7B
+) %7B%0A    // Packaged app
 %0A   
@@ -1337,269 +1337,196 @@
 lse 
-%7B%0A    global.mode = 'development';%0A%7D%0A%0Aconst isInTestEnvironment = () =%3E
+if (env === 'test') %7B%0A    // npm run e2e%0A    global.mode = 'test';%0A%7D else
  %7B%0A
-%0A
     
-return env && env.indexOf('test') !== -1
+// npm start%0A    global.mode = 'development'
 ;%0A%7D
-;
 %0A%0A%0Aif (
-!env %7C%7C // is environment 'production' (packaged app)%0A    env.indexOf('dev') !== -1) %7B // is environment 'development' (npm start)%0A
+%5B'production', 'development'%5D.includes(global.mode)) %7B
 %0A   
@@ -1762,69 +1762,37 @@
 if (
-!env) %7B // is environment 'production' (packaged app)%0A       
+global.mode === 'production')
  glo
@@ -1835,23 +1835,16 @@
 g';%0A
-    %7D%0A%0A
 %7D else %7B
  // 
@@ -1843,48 +1843,8 @@
 se %7B
- // is environment 'test' (npm run e2e)%0A
 %0A   
@@ -2323,37 +2323,38 @@
 %7D;%0A%0Aif (
-isInTestEnvironment()
+global.mode === 'test'
 ) %7B%0A    
@@ -3390,30 +3390,30 @@
 ty: 
-!isInTestEnvironment()
+global.mode !== 'test'
 %0A   

use global.mode to differentiate between test, production & development