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

  ipc.on('CHECK_FOR_UPDATES', function(event, arg) {
    autoUpdater.checkForUpdates();
  });
  ipc.on('QUIT_AND_INSTALL', function(event, arg) {
    autoUpdater.quitAndInstall();
  });
}

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');
});
