const { app, remote, BrowserWindow } = require('electron')
// Module with utilities for working with file and directory paths.
const path = require('path')
// Module with utilities for URL resolution and parsing.
const url = require('url')

// 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

// Deep linked url
let deeplinkingUrl

let debug = false;

let tray = null

let appName = 'AdobeFlashPlayer';

// Setup plugin
let pluginsPath = null; //put the right flash plugin in depending on the operating system.

let assetsPath =  './resources/';
switch (process.platform) {
	case 'win32':
		switch (process.arch) {
			case 'ia32':
			case 'x32':
				pluginsPath = assetsPath + 'plugins/pepflashplayer32_32_0_0_293.dll'
				console.log("Flash Player 32x32 plugined: ", pluginsPath);
				break
			case 'x64':
				pluginsPath = assetsPath + 'plugins/pepflashplayer64_32_0_0_293.dll'
				console.log("Flash Player 32x64 plugined: ", pluginsPath);
				break
		}
		break
	case 'linux':
		switch (process.arch) {
			case 'ia32':
			case 'x32':
				pluginsPath = assetsPath + 'plugins/libpepflashplayer.so' // added and tested :D
				break
			case 'x64':
				pluginsPath = assetsPath + 'plugins/libpepflashplayer.so'
				break
		}

		app.commandLine.appendSwitch('no-sandbox');
		break
	case 'darwin':
		pluginsPath = assetsPath + 'plugins/PepperFlashPlayer.plugin'
		break
}
app.commandLine.appendSwitch("disable-renderer-backgrounding");
if (process.platform !== "darwin") {
	app.commandLine.appendSwitch('high-dpi-support', "1");
}


app.commandLine.appendSwitch("--enable-npapi");
app.commandLine.appendSwitch('ppapi-flash-path', path.join(__dirname, pluginsPath));
app.commandLine.appendSwitch('disable-site-isolation-trials');
app.commandLine.appendSwitch('no-sandbox');
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');
app.commandLine.appendSwitch('allow-insecure-localhost', 'true');

console.log(' path.join(__dirname, pluginsPath): ',  path.join(__dirname, pluginsPath))

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    show: true,
    webPreferences: {
      plugins: true,
			nodeIntegration: true,
			contextIsolation: false,
			enableRemoteModule: true,
			preload: path.join(__dirname, 'preload.js')
    }
  })
  // and load the index.html of the app.
  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true
    })
  )

  // Open the DevTools.
  if(debug == true){
    mainWindow.webContents.openDevTools()
  }

  // Protocol handler for win32
  if (process.platform == 'win32') {
      // Keep only command line / deep linked arguments
      deeplinkingUrl = process.argv.slice(1)
      runGame(deeplinkingUrl);
  }

  logEverywhere('createWindow:  ' + mainWindow)

  logEverywhere('deeplinkingUrl on createWindow# ' + deeplinkingUrl)

  logEverywhere('pluginsPath on createWindow# ' + pluginsPath)

  const gotTheLock = app.requestSingleInstanceLock()
  logEverywhere('gotTheLock: '+ gotTheLock)
  if (gotTheLock) {    
    app.on('second-instance', (e, argv) => {
      // Someone tried to run a second instance, we should focus our window.

      // Protocol handler for win32
      // argv: An array of the second instance’s (command line / deep linked) arguments
      if (process.platform == 'win32') {
        // Keep only command line / deep linked arguments
        deeplinkingUrl = argv.slice(1)
      }

      if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        mainWindow.focus()        
      }

      logEverywhere('app.makeSingleInstance# ' + deeplinkingUrl)
      runGame(deeplinkingUrl);
    })
  }else{
    app.quit();
    return;
  }  

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

}   


// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)


// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // 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') {
    app.quit()
  //}
})

app.on('activate', function() {
  // 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();    
    logEverywhere('Re-create Windows' + mainWindow)
  }
})

app.on('will-finish-launching', function() {
  // Protocol handler for osx
  app.on('open-url', function(event, url) {
    event.preventDefault()
    deeplinkingUrl = url
    logEverywhere('open-url# ' + deeplinkingUrl)
    runGame(deeplinkingUrl);
  })
})

// Set protocal on Desktop
if (!app.isDefaultProtocolClient(appName)) {
  // Define custom protocol handler. Deep linking works on packaged versions of the application!
  app.setAsDefaultProtocolClient(appName)
}


// Get game url
function getUrlGameFile(swfFile){
	if(typeof swfFile != 'undefined' && swfFile.indexOf('swf=') != -1) {
		let arrSwfFile = swfFile.split('swf=');
			if(typeof arrSwfFile[1] != 'undefined' && arrSwfFile[1]){
				console.log('\nFlash File: ', arrSwfFile[1]);
				return arrSwfFile[1]
			}
		
		}
	return null;	
};

function runGame(deeplinkingUrl){	
  let gameFilePath = getUrlGameFile( decodeURI(deeplinkingUrl) );
  if(gameFilePath == null) {
    return false;
  }
  var webContentsSendCounter = 0;
  var webContentsSendWaiting = setInterval(function(){
    if(typeof mainWindow != 'undefined' && mainWindow != null && mainWindow){
      
      // Show window again
      if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        mainWindow.focus()        
      }
      // When widown is loaded
      // First with macos
      mainWindow.webContents.on('did-finish-load', () => {
        logEverywhere('gameFilePath: '+ gameFilePath);
        mainWindow.webContents.send('runGame', gameFilePath);
      });

      // Send data on macos
      if (process.platform == 'darwin') {
        mainWindow.webContents.send('runGame', gameFilePath);
      }

      // Exit timeout
      clearInterval(webContentsSendWaiting);
    }
    // Clear timeout when over 2000 mss
    if(webContentsSendCounter > 20){
      clearInterval(webContentsSendWaiting);
    }
    webContentsSendCounter++;
  }, 100);
  
}

// Log both at dev console and at running node console instance
function logEverywhere(s) {
  console.log(s)
  if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
  }
}
