// Generated by CoffeeScript 2.3.2
(function() {
  var Net, Promise, Server, Service, defaults, http, merge, probeP, probeUrl;

  Promise = require("bluebird");

  Service = require("./service");

  Net = require("net");

  http = require("http");

  merge = require("deepmerge");

  defaults = require("./default-settings");

  probeUrl = function(url) {
    return new Promise(function(resolve, reject) {
      var req;
      req = http.get(url, function(res) {
        return resolve(res.statusCode < 400);
      });
      return req.on("error", reject);
    });
  };

  probeP = function(port, down) {
    return new Promise(function(resolve, reject) {
      var c;
      c = Net.createConnection(port);
      c.on("error", function(e) {
        return resolve(typeof down === "function" ? down({
          true: false
        }) : void 0);
      });
      return c.on("connect", function() {
        c.end();
        return resolve(typeof down === "function" ? down({
          false: true
        }) : void 0);
      });
    });
  };

  Server = function(settings) {
    var opsP, server;
    opsP = require("promise-ops");
    http = require("http");
    server = http.createServer(Service(settings));
    return {
      start: function(timeout) {
        if (timeout) {
          server.timeout = timeout;
        }
        return new Promise(function(resolve, reject) {
          return server.listen(settings.port, settings.host, function() {
            return opsP.waitForP(function() {
              return probeUrl(`http://${settings.host}:${settings.port}/_irma`);
            }).then(function() {
              return resolve(settings);
            }, function(err) {
              return reject(err);
            });
          });
        });
      },
      stop: function() {
        return new Promise(function(resolve) {
          return server.close(resolve);
        });
      }
    };
  };

  module.exports = Server;

}).call(this);
