var app = require('app');
var BrowserWindow = require('browser-window');
var shell = require('shell');
var ipc = require('ipc');
var singleInstance = require('./single-instance');

var WIDTH = 1280;
var HEIGHT = 720;

var mainWindow = null;

function webContentsSend(/* arguments */) {
  if (mainWindow != null && mainWindow.webContents != null) {
    mainWindow.webContents.send.apply(mainWindow.webContents, arguments);
  }
}

var autoUpdater;
if (process.platform === 'darwin') {
  autoUpdater = require('auto-updater');
  autoUpdater.setFeedUrl('https://discordapp.com/api/updates?version=' + app.getVersion());
}
else if (process.platform === 'win32') {
  autoUpdater = require('./auto-updater-win32');
  // Squirrel for Windows can't handle query params
  // https://github.com/Squirrel/Squirrel.Windows/issues/132
  autoUpdater.setFeedUrl('https://discordapp.com/api/updates');
}

if (autoUpdater != null) {
  var autoUpdaterState = 'UPDATE_NOT_AVAILABLE';
  autoUpdater.on('checking-for-update', function() {
    autoUpdaterState = 'CHECKING_FOR_UPDATES';
    webContentsSend(autoUpdaterState);
  });
  autoUpdater.on('update-not-available', function() {
    autoUpdaterState = 'UPDATE_NOT_AVAILABLE';
    webContentsSend(autoUpdaterState);
  });
  autoUpdater.on('update-available', function() {
    autoUpdaterState = 'UPDATE_AVAILABLE';
    webContentsSend(autoUpdaterState);
  });
  autoUpdater.on('error', function(event, message) {
    autoUpdaterState = 'UPDATE_NOT_AVAILABLE';
    webContentsSend('UPDATE_ERROR', message);
  });
  autoUpdater.on('update-downloaded', function(event, releaseNotes, releaseName, releaseDate, updateUrl) {
    autoUpdaterState = 'UPDATE_DOWNLOADED';
    webContentsSend(autoUpdaterState, releaseNotes, releaseName, releaseDate, updateUrl);
  });

  ipc.on('CHECK_FOR_UPDATES', function(event, arg) {
    if (autoUpdaterState === 'UPDATE_NOT_AVAILABLE') {
      autoUpdater.checkForUpdates();
    }
    else {
      webContentsSend(autoUpdaterState);
    }
  });
  ipc.on('QUIT_AND_INSTALL', function(event, arg) {
    autoUpdater.quitAndInstall();
  });
}

app.on('window-all-closed', function() {
  app.quit();
});

app.on('ready', function() {
  singleInstance(
    'discord',
    function() {
      if (autoUpdater != null) {
        autoUpdater.checkForUpdates();
      }
      
      mainWindow = new BrowserWindow({
        width: WIDTH,
        height: HEIGHT,
        'min-width': WIDTH,
        'min-height': HEIGHT,
        transparent: false,
        frame: false,
        resizable: true
      });
      mainWindow.webContents.on('new-window', function(e, url) {
        e.preventDefault();
        shell.openExternal(url);
      });
      mainWindow.on('closed', function() {
        mainWindow = null;
      });
      mainWindow.loadUrl('https://discordapp.com/?_=' + Date.now());
    },
    function() {
      if (mainWindow != null) {
        mainWindow.focus();
      }
    }
  );
});
