// Generated by IcedCoffeeScript 1.8.0-a
(function() {
  var E, KeySelector, find_key_id_64, format, gpg, iced, load_key, log, log_10, make_esc, master_ring, pad, prompt_for_int, repeat, spc, tablify, unix_time, __iced_k, __iced_k_noop, _ref;

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

  log = require('./log');

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

  make_esc = require('iced-error').make_esc;

  prompt_for_int = require('./prompter').prompt_for_int;

  _ref = require('./keyring'), master_ring = _ref.master_ring, load_key = _ref.load_key;

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

  format = require('pgp-utils').userid.format;

  tablify = require('tablify').tablify;

  unix_time = require('iced-utils').util.unix_time;

  find_key_id_64 = function(raw) {
    var m, x;
    x = /^(?:pub|sec)\s+[0-9]{4}(?:R|D)\/([0-9A-F]{16}) /;
    if ((m = raw.match(x))) {
      return m[1];
    } else {
      return null;
    }
  };

  log_10 = function(x) {
    var val;
    val = 0;
    while (x > 0) {
      val++;
      x = Math.floor(x / 10);
    }
    return val;
  };

  pad = function(i, places) {
    var n;
    n = places - (log_10(i));
    if (n < 0) {
      n = 0;
    }
    return spc(n) + i;
  };

  spc = function(i) {
    return repeat(' ', i);
  };

  repeat = function(c, i) {
    return ((function() {
      var _i, _results;
      _results = [];
      for (_i = 0; 0 <= i ? _i < i : _i > i; 0 <= i ? _i++ : _i--) {
        _results.push(c);
      }
      return _results;
    })()).join('');
  };

  exports.KeySelector = KeySelector = (function() {
    function KeySelector(_arg) {
      this.username = _arg.username, this.query = _arg.query, this.secret = _arg.secret;
    }

    KeySelector.prototype.select = function(cb) {
      var err, esc, key, keys, km, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "KeySelector::select");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/mpj/Projects/node-client/src/keyselector.iced",
            funcname: "KeySelector.select"
          });
          _this.query_keys(esc(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return keys = arguments[0];
              };
            })(),
            lineno: 42
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if (keys.length > 1) {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/mpj/Projects/node-client/src/keyselector.iced",
                  funcname: "KeySelector.select"
                });
                _this.select_key(keys, esc(__iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      return key = arguments[0];
                    };
                  })(),
                  lineno: 44
                })));
                __iced_deferrals._fulfill();
              })(__iced_k);
            } else {
              return __iced_k(keys.length === 1 ? key = keys[0] : key = null);
            }
          })(function() {
            err = null;
            (function(__iced_k) {
              if (typeof key !== "undefined" && key !== null) {
                (function(__iced_k) {
                  __iced_deferrals = new iced.Deferrals(__iced_k, {
                    parent: ___iced_passed_deferral,
                    filename: "/home/mpj/Projects/node-client/src/keyselector.iced",
                    funcname: "KeySelector.select"
                  });
                  load_key({
                    username: _this.username,
                    fingerprint: key.fingerprint()
                  }, esc(__iced_deferrals.defer({
                    assign_fn: (function() {
                      return function() {
                        return km = arguments[0];
                      };
                    })(),
                    lineno: 51
                  })));
                  __iced_deferrals._fulfill();
                })(__iced_k);
              } else {
                return __iced_k(err = new E.NoLocalKeyError("No local keys found! Try `keybase gen` to generate one."));
              }
            })(function() {
              return cb(err, km);
            });
          });
        };
      })(this));
    };

    KeySelector.prototype.query_keys = function(cb) {
      var err, index, key, keys, opts, warnings, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      opts = {
        secret: this.secret,
        query: this.query
      };
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/mpj/Projects/node-client/src/keyselector.iced",
            funcname: "KeySelector.query_keys"
          });
          master_ring().index2(opts, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                index = arguments[1];
                return warnings = arguments[2];
              };
            })(),
            lineno: 60
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          keys = typeof err !== "undefined" && err !== null ? null : (function() {
            var _i, _len, _ref1, _results;
            _ref1 = index.keys();
            _results = [];
            for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
              key = _ref1[_i];
              if (!key.is_revoked()) {
                _results.push(key);
              }
            }
            return _results;
          })();
          return cb(err, keys);
        };
      })(this));
    };

    KeySelector.prototype.longest_line = function(keys) {
      var key, l, line, longest, _i, _j, _len, _len1, _ref1;
      longest = 0;
      for (_i = 0, _len = keys.length; _i < _len; _i++) {
        key = keys[_i];
        _ref1 = key.lines;
        for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
          line = _ref1[_j];
          if ((l = line.length) > longest) {
            longest = l;
          }
        }
      }
      return longest;
    };

    KeySelector.prototype.format_ts = function(t, zero_val) {
      var d, s;
      if (zero_val == null) {
        zero_val = "n/a";
      }
      if ((t != null) && t) {
        d = new Date(t * 1000);
        return ((function() {
          var _i, _len, _ref1, _results;
          _ref1 = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            s = _ref1[_i];
            _results.push("" + s);
          }
          return _results;
        })()).join('-');
      } else {
        return zero_val;
      }
    };

    KeySelector.prototype.key_to_array = function(key) {
      var args;
      args = [key._n_bits + (key._type === 1 ? 'R' : 'D'), key.key_id_64(), "exp: " + (this.format_ts(key._expires, 'never'))].concat(key.emails());
      return args;
    };

    KeySelector.prototype.select_key_menu = function(keys) {
      var i, key, list, _i, _len;
      list = [];
      for (i = _i = 0, _len = keys.length; _i < _len; i = ++_i) {
        key = keys[i];
        list.push(["(" + (i + 1) + ")"].concat(this.key_to_array(key)));
      }
      return log.console.log(tablify(list, {
        row_start: ' ',
        row_end: '',
        spacer: '  ',
        row_sep_char: ''
      }));
    };

    KeySelector.prototype.select_key = function(keys, cb) {
      var err, key, out, pcmp, prompt, sel, ___iced_passed_deferral, __iced_deferrals, __iced_k, _i, _len;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      if (this.query) {
        log.console.log("Multiple keys were found that matched '" + this.query + "':");
      } else {
        log.console.log("Multiple keys found, please pick one:");
      }
      for (_i = 0, _len = keys.length; _i < _len; _i++) {
        key = keys[_i];
        key.s = [key.emails().length, key._expires || 10e11];
      }
      pcmp = function(a, b) {
        var ret;
        ret = a[0] < b[0] ? 1 : a[0] > b[0] ? -1 : a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0;
        return ret;
      };
      keys.sort(function(a, b) {
        return pcmp(a.s, b.s);
      });
      this.select_key_menu(keys);
      prompt = "Pick a key";
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/mpj/Projects/node-client/src/keyselector.iced",
            funcname: "KeySelector.select_key"
          });
          prompt_for_int({
            prompt: prompt,
            low: 1,
            hi: keys.length
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return sel = arguments[1];
              };
            })(),
            lineno: 126
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          out = typeof err !== "undefined" && err !== null ? null : keys[sel - 1];
          if (out != null) {
            log.info("Picked key: " + (out.key_id_64()));
          }
          return cb(err, out);
        };
      })(this));
    };

    return KeySelector;

  })();

  exports.key_select = function(_arg, cb) {
    var query, secret, username;
    username = _arg.username, query = _arg.query, secret = _arg.secret;
    return (new KeySelector({
      username: username,
      query: query,
      secret: secret
    })).select(cb);
  };

}).call(this);
