var app = require('app');
var BrowserWindow = require('browser-window');
var shell = require('shell');
var ipc = require('ipc');

var WIDTH = 1280;
var HEIGHT = 720;

var mainWindow = null;

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';
    mainWindow.webContents.send(autoUpdaterState);
  });
  autoUpdater.on('update-not-available', function() {
    autoUpdaterState = 'UPDATE_NOT_AVAILABLE';
    mainWindow.webContents.send(autoUpdaterState);
  });
  autoUpdater.on('update-available', function() {
    autoUpdaterState = 'UPDATE_AVAILABLE';
    mainWindow.webContents.send(autoUpdaterState);
  });
  autoUpdater.on('error', function(event, message) {
    autoUpdaterState = 'UPDATE_NOT_AVAILABLE';
    mainWindow.webContents.send('UPDATE_ERROR', message);
  });
  autoUpdater.on('update-downloaded', function(event, releaseNotes, releaseName, releaseDate, updateUrl) {
    autoUpdaterState = 'UPDATE_DOWNLOADED';
    mainWindow.webContents.send(autoUpdaterState, releaseNotes, releaseName, releaseDate, updateUrl);
  });

  ipc.on('CHECK_FOR_UPDATES', function(event, arg) {
    if (autoUpdaterState === 'UPDATE_NOT_AVAILABLE') {
      autoUpdater.checkForUpdates();
    }
    else if (mainWindow != null) {
      mainWindow.webContents.send(autoUpdaterState);
    }
  });
  ipc.on('QUIT_AND_INSTALL', function(event, arg) {
    autoUpdater.quitAndInstall();
  });
  
  autoUpdater.checkForUpdates();
}

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

app.on('ready', function() {
  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');
});
