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

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

function extractPath(args, fallbackPath) {
  if (args[0] === '--url') {
    var parsedURL = url.parse(args[1]);
    if (parsedURL.protocol === 'discord:') {
      return parsedURL.path;
    }
  }
  return fallbackPath;
}

function main() {
  if (process.platform === 'win32') {
    var SquirrelUpdate = require('./squirrel-update');
    var squirrelCommand = process.argv[1];
    if (SquirrelUpdate.handleStartupEvent('Discord', app, squirrelCommand)) {
      return;
    }
  }

  var path = extractPath(process.argv.slice(1), '/channels/@me');

  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('open-url', function(event, openURL) {
    var parsedURL = url.parse(openURL);
    if (parsedURL.protocol === 'discord:') {
      if (mainWindow == null) {
        path = parsedURL.path;
      }
      else {
        webContentsSend('PATH', parsedURL.path);
      }
    }
  });

  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, windowURL) {
          e.preventDefault();
          shell.openExternal(windowURL);
        });
        mainWindow.on('closed', function() {
          mainWindow = null;
        });
        mainWindow.loadUrl('https://discordapp.com' + path + '?_=' + Date.now());
      },
      function(args) {
        if (mainWindow != null) {
          path = extractPath(args);
          if (path != null) {
            webContentsSend('PATH', path);
          }
          mainWindow.focus();
        }
      }
    );
  });
}

main();
