var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.
var ipc = require('ipc');


// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
var canExit = false;
var openFile = false;


ipc.on('synchronous-message', function(event, arg) {
 if(arg == "forcing-quit"){  // prints "ping"
   canExit = true;
   app.quit();
 }
});

app.on('open-file', function(event, pathToOpen) {

 openFile = true;

 // respond to the process...
 ipc.on('synchronous-message', function(event, arg) {  
   if(arg == "starts-whit-path")
     event.returnValue = pathToOpen;
 });

});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
 // Create the browser window.
 mainWindow = new BrowserWindow({width: 800, height: 600, title : "Pingendo", "web-preferences": {
     "web-security": false
 }});

 // and load the index.html of the app.
 mainWindow.loadUrl('file://' + __dirname + '/index.html');
 // mainWindow.loadUrl('http://v4.pingendo.com/index.html');
 // mainWindow.loadUrl('http://127.0.0.1:5000/index.html');

 if(!openFile){
    // respond to the process...
   ipc.on('synchronous-message', function(event, arg) {
     if(arg == "starts-whit-path")
       event.returnValue = null;
   });
 }

 // Open the devtools.
 // mainWindow.openDevTools();

 mainWindow.on('close', function(event){
     if(!canExit){
       event.preventDefault();
       mainWindow.webContents.send('before-quit','');
     }
 })


});


app.on('before-quit', function(event) {
   if(!canExit){
     event.preventDefault();
     mainWindow.webContents.send('before-quit','');
   }
});