// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var E, HKPLoopback, env, http, iced, log, reqmod, urlmod, __iced_k, __iced_k_noop;

  iced = require('iced-runtime').iced;
  __iced_k = __iced_k_noop = function() {};

  http = require('http');

  env = require('./env').env;

  reqmod = require('./req');

  log = require('./log');

  E = require('./env').E;

  urlmod = require('url');

  exports.HKPLoopback = HKPLoopback = (function() {
    function HKPLoopback() {
      this._srv = http.createServer(this.serve.bind(this));
      this._port = null;
      this._hostname = "127.0.0.1";
    }

    HKPLoopback.prototype.url = function() {
      return "hkp://" + this._hostname + ":" + this._port + "/";
    };

    HKPLoopback.prototype.listen = function(cb) {
      var err, p, r, ___iced_passed_deferral, __iced_deferrals, __iced_k, _begin, _end, _positive;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      log.debug("+ HKPLoopback::init; hunt for a port");
      r = env().get_loopback_port_range();
      (function(_this) {
        return (function(__iced_k) {
          var _i, _results, _while;
          p = r[0];
          _begin = r[0];
          _end = r[1];
          _positive = _end > _begin;
          _results = [];
          _while = function(__iced_k) {
            var _break, _continue, _next;
            _break = function() {
              return __iced_k(_results);
            };
            _continue = function() {
              return iced.trampoline(function() {
                if (_positive) {
                  p += 1;
                } else {
                  p -= 1;
                }
                return _while(__iced_k);
              });
            };
            _next = function(__iced_next_arg) {
              _results.push(__iced_next_arg);
              return _continue();
            };
            if (!!((_positive === true && p > r[1]) || (_positive === false && p < r[1]))) {
              return _break();
            } else {

              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/Users/max/src/keybase/node-client/src/hkp_loopback.iced",
                  funcname: "HKPLoopback.listen"
                });
                _this._srv.listen(p, _this._hostname, __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      return err = arguments[0];
                    };
                  })(),
                  lineno: 23
                }));
                __iced_deferrals._fulfill();
              })(function() {
                (function(__iced_k) {
                  if (err == null) {
                    log.debug("| found " + p);
                    _this._port = p;
                    (function(__iced_k) {
_break()
                    })(__iced_k);
                  } else {
                    return __iced_k();
                  }
                })(_next);
              });
            }
          };
          _while(__iced_k);
        });
      })(this)((function(_this) {
        return function() {
          err = _this._port != null ? null : new E.LoopbackError("no available ports found");
          log.debug("- HKPLoopback::init -> " + err);
          return cb(err);
        };
      })(this));
    };

    HKPLoopback.prototype.serve = function(req, res) {
      var body, err, gres, inurl, opts, u, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      u = req.url;
      log.debug("+ Incoming HKP request on loopback :" + this._port + ": " + u);
      inurl = urlmod.parse(u);
      opts = {
        json: false,
        jar: false,
        pathname: inurl.pathname,
        search: inurl.search
      };
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/node-client/src/hkp_loopback.iced",
            funcname: "HKPLoopback.serve"
          });
          reqmod.get(opts, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                body = arguments[1];
                return gres = arguments[2];
              };
            })(),
            lineno: 41
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          gres.headers['connection'] = 'close';
          res.writeHead(gres.statusCode, gres.headers);
          res.write(gres.body);
          log.debug("- Replied to loopback request w/ status=" + gres.statusCode);
          return res.end();
        };
      })(this));
    };

    HKPLoopback.prototype.close = function(cb) {
      var ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      (function(_this) {
        return (function(__iced_k) {
          if (_this._srv != null) {
            (function(__iced_k) {
              __iced_deferrals = new iced.Deferrals(__iced_k, {
                parent: ___iced_passed_deferral,
                filename: "/Users/max/src/keybase/node-client/src/hkp_loopback.iced",
                funcname: "HKPLoopback.close"
              });
              _this._srv.close(__iced_deferrals.defer({
                lineno: 50
              }));
              __iced_deferrals._fulfill();
            })(__iced_k);
          } else {
            return __iced_k();
          }
        });
      })(this)((function(_this) {
        return function() {
          return cb(null);
        };
      })(this));
    };

    return HKPLoopback;

  })();

}).call(this);
