var app = require('app');
var net = require('net');
var path = require('path');
var fs = require('fs');
var os = require('os');

var defaultSocketPath;

if (process.platform === 'win32') {
  defaultSocketPath = '\\\\.\\pipe\\discord-sock'
}
else {
  defaultSocketPath = path.join(os.tmpdir(), 'discord.sock')
}

app.on('will-quit', function() {
  // deleteSocketFile
});

app.on('will-exit', function() {
  // deleteSocketFile
});

function deleteSocketFile(options) {
  if (process.platform === 'win32') {
    return;
  }

  if (fs.existsSync(options.socketPath)) {
    try {
      fs.unlinkSync(options.socketPath);
    }
    catch (error) {
      // Ignore ENOENT errors in case the file was deleted between the exists
      // check and the call to unlink sync. This occurred occasionally on CI
      // which is why this check is here.
      if (error.code !== 'ENOENT') {
        throw error;
      }
    }
  }
}

// Creates server to listen for additional atom application launches.
//
// You can run the atom command multiple times, but after the first launch
// the other launches will just pass their information to this server and then
// close immediately.
function listenForArgumentsFromNewProcess(options) {
  deleteSocketFile(options);

  var server = net.createServer(function(connection) {
    connection.on('data', function(data) {
      var options = JSON.parse(data);
      // TODO: do something with options
    });
  });
  server.listen(options.socketPath);
  server.on('error', function(error) {
    console.error('Application server failed', error);
  });
}

function tryStart(options, callback) {
  options.socketPath = options.socketPath || defaultSocketPath;

  // FIXME: Sometimes when socketPath doesn't exist, net.connect would strangely
  // take a few seconds to trigger 'error' event, it could be a bug of node
  // or atom-shell, before it's fixed we check the existence of socketPath to
  // speedup startup.
  if (process.platform !== 'win32' && !fs.existsSync(options.socketPath)) {
    callback()
    return
  }

  var client = net.connect({path: options.socketPath}, function() {
    client.write(JSON.stringify(options), function() {
      client.end();
      app.terminate();
    });
  });
  client.on('error', callback);
}
