import app from 'app';
import BrowserWindow from 'browser-window';
import shell from 'shell';
import ipc from 'ipc';

const WIDTH = 1280;
const HEIGHT = 720;

let mainWindow = null;

function webContentsSend(...args) {
  if (mainWindow != null && mainWindow.webContents != null) {
    mainWindow.webContents(...args);
  }
}

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

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

  autoUpdater.checkForUpdates();
}

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

export default 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', (e, url) => {
    e.preventDefault();
    shell.openExternal(url);
  });
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
  mainWindow.loadUrl('https://discordapp.com/?_=' + Date.now());
}
