// Generated by IcedCoffeeScript 1.7.1-c
(function() {
  var DB, Lock, chain, constants, env, fs, iced, idb, iutils, k, log, make_esc, make_key, make_kvstore_key, make_lookup_key, mkdirp, path, util, v, __iced_k, __iced_k_noop, _db, _fn, _ref, _ref1,
    __slice = [].slice;

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

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

  fs = require('fs');

  path = require('path');

  _ref = require('iced-error'), chain = _ref.chain, make_esc = _ref.make_esc;

  mkdirp = require('./fs').mkdirp;

  iutils = require('iced-utils');

  Lock = iutils.lock.Lock;

  util = require('pgp-utils').util;

  log = require('./log');

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

  idb = require('iced-db');

  make_key = function(_arg) {
    var id, table, type;
    table = _arg.table, type = _arg.type, id = _arg.id;
    return [table, type, id].join(":").toLowerCase();
  };

  make_kvstore_key = function(_arg) {
    var key, type;
    type = _arg.type, key = _arg.key;
    type || (type = key.slice(-2));
    return make_key({
      table: "kv",
      type: type,
      id: key
    });
  };

  make_lookup_key = function(_arg) {
    var name, type;
    type = _arg.type, name = _arg.name;
    return make_key({
      table: "lo",
      type: type,
      id: name
    });
  };

  DB = (function() {
    function DB(_arg) {
      this.filename = _arg.filename;
      this.lock = new Lock;
    }

    DB.prototype.get_db = function() {
      var db;
      return db = new idb.DB({
        root: this.get_filename(),
        json: true
      });
    };

    DB.prototype.get_filename = function() {
      this.filename || (this.filename = env().get_db_filename());
      return this.filename;
    };

    DB.prototype._upgrade = function(cb) {
      var err, f, so, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      f = env().get_nedb_filename();
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB._upgrade"
          });
          fs.stat(f, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return so = arguments[1];
              };
            })(),
            lineno: 44
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if (typeof err === "undefined" || err === null) {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/jacko/node-client/src/db.iced",
                  funcname: "DB._upgrade"
                });
                fs.unlink(f, __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      return err = arguments[0];
                    };
                  })(),
                  lineno: 46
                }));
                __iced_deferrals._fulfill();
              })(function() {
                return __iced_k(typeof err !== "undefined" && err !== null ? log.warn("Error deleting old DB file " + f + ": " + err) : log.info("Deleting old DB " + f));
              });
            } else {
              return __iced_k();
            }
          })(function() {
            return cb(err);
          });
        };
      })(this));
    };

    DB.prototype.open = function(cb) {
      var err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      err = null;
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.open"
          });
          _this._upgrade(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 57
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if (_this.db == null) {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/jacko/node-client/src/db.iced",
                  funcname: "DB.open"
                });
                _this._open(__iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      return err = arguments[0];
                    };
                  })(),
                  lineno: 58
                }));
                __iced_deferrals._fulfill();
              })(__iced_k);
            } else {
              return __iced_k();
            }
          })(function() {
            return cb(err);
          });
        };
      })(this));
    };

    DB.prototype.unlink = function(cb) {
      var db, err, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      db = this.get_db();
      log.info("Purging local cache: " + db.root);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.unlink"
          });
          db.drop(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 66
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(err);
        };
      })(this));
    };

    DB.prototype.close = function(cb) {
      return cb(null);
    };

    DB.prototype._open = function(cb) {
      var err, esc, fn, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      esc = make_esc(cb, "DB::open");
      err = null;
      fn = this.get_filename();
      log.debug("+ opening database file: " + fn);
      this.db = this.get_db();
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB._open"
          });
          _this._init_db(esc(__iced_deferrals.defer({
            lineno: 82
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          log.debug("- DB opened");
          return cb(null);
        };
      })(this));
    };

    DB.prototype.put = function(_arg, cb) {
      var debug, err, hkey, json, key, kvsk, lk, name, names, obj, tmp, type, value, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      type = _arg.type, key = _arg.key, value = _arg.value, name = _arg.name, names = _arg.names, debug = _arg.debug, json = _arg.json;
      kvsk = make_kvstore_key({
        type: type,
        key: key
      });
      if (debug) {
        log.debug("| DB put value " + kvsk);
      }
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.put"
          });
          _this.db.put({
            key: kvsk,
            value: value,
            json: json
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return obj = arguments[1];
              };
            })(),
            lineno: 91
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if (typeof err === "undefined" || err === null) {
              hkey = obj.hkey;
              if ((name != null) && (names == null)) {
                names = [name];
              }
              (function(__iced_k) {
                if (names && names.length) {
                  (function(__iced_k) {
                    var _i, _len, _ref1, _results, _while;
                    _ref1 = names;
                    _len = _ref1.length;
                    _i = 0;
                    _results = [];
                    _while = function(__iced_k) {
                      var _break, _continue, _next;
                      _break = function() {
                        return __iced_k(_results);
                      };
                      _continue = function() {
                        return iced.trampoline(function() {
                          ++_i;
                          return _while(__iced_k);
                        });
                      };
                      _next = function(__iced_next_arg) {
                        _results.push(__iced_next_arg);
                        return _continue();
                      };
                      if (!(_i < _len)) {
                        return _break();
                      } else {
                        name = _ref1[_i];
                        lk = make_lookup_key(name);
                        if (debug) {
                          log.debug("| DB put lookup: " + lk + " -> " + hkey);
                        }
                        (function(__iced_k) {
                          __iced_deferrals = new iced.Deferrals(__iced_k, {
                            parent: ___iced_passed_deferral,
                            filename: "/home/jacko/node-client/src/db.iced",
                            funcname: "DB.put"
                          });
                          _this.db.put({
                            key: lk,
                            value: hkey
                          }, __iced_deferrals.defer({
                            assign_fn: (function() {
                              return function() {
                                return tmp = arguments[0];
                              };
                            })(),
                            lineno: 99
                          }));
                          __iced_deferrals._fulfill();
                        })(function() {
                          return _next((typeof tmp !== "undefined" && tmp !== null) && (typeof err === "undefined" || err === null) ? err = tmp : void 0);
                        });
                      }
                    };
                    _while(__iced_k);
                  })(__iced_k);
                } else {
                  return __iced_k();
                }
              })(__iced_k);
            } else {
              return __iced_k();
            }
          })(function() {
            return cb(err);
          });
        };
      })(this));
    };

    DB.prototype.remove = function(_arg, cb) {
      var err, k, key, optional, type, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      type = _arg.type, key = _arg.key, optional = _arg.optional;
      k = make_kvstore_key({
        type: type,
        key: key
      });
      err = null;
      log.debug("+ DB remove " + k);
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.remove"
          });
          _this.db.del({
            key: k
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return err = arguments[0];
              };
            })(),
            lineno: 112
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if ((err != null) && (err instanceof idb.E.NotFoundError) && optional) {
            log.debug("| No object found for " + k);
            err = null;
          }
          log.debug("- DB remove " + k + " -> " + err);
          return cb(null);
        };
      })(this));
    };

    DB.prototype.find1 = function(q, cb) {
      var err, value, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      err = value = null;
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.find1"
          });
          _this.db.get(q, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return value = arguments[1];
              };
            })(),
            lineno: 125
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          if ((err != null) && (err instanceof idb.E.NotFoundError)) {
            err = null;
          } else if (err != null) {

          }
          return cb(err, value);
        };
      })(this));
    };

    DB.prototype.get = function(_arg, cb) {
      var err, json, k, key, type, value, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      type = _arg.type, key = _arg.key, json = _arg.json;
      k = make_kvstore_key({
        type: type,
        key: key
      });
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.get"
          });
          _this.find1({
            key: k,
            json: json
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return value = arguments[1];
              };
            })(),
            lineno: 134
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          return cb(err, value);
        };
      })(this));
    };

    DB.prototype.lookup = function(_arg, cb) {
      var err, k, name, type, value, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      type = _arg.type, name = _arg.name;
      k = make_lookup_key({
        type: type,
        name: name
      });
      err = value = null;
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB.lookup"
          });
          _this.find1({
            key: k
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return value = arguments[1];
              };
            })(),
            lineno: 142
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          (function(__iced_k) {
            if ((err == null) && (value != null)) {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/jacko/node-client/src/db.iced",
                  funcname: "DB.lookup"
                });
                _this.find1({
                  hkey: value
                }, __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      err = arguments[0];
                      return value = arguments[1];
                    };
                  })(),
                  lineno: 144
                }));
                __iced_deferrals._fulfill();
              })(__iced_k);
            } else {
              return __iced_k();
            }
          })(function() {
            return cb(err, value);
          });
        };
      })(this));
    };

    DB.prototype._init_db = function(cb) {
      var esc, made, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      log.debug("+ DB::_init_db");
      esc = make_esc(cb, "DB::_init_db");
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/jacko/node-client/src/db.iced",
            funcname: "DB._init_db"
          });
          _this.db.create(esc(__iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                return made = arguments[0];
              };
            })(),
            lineno: 152
          })));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          log.debug("- DB::_init_db -> " + made);
          return cb(null);
        };
      })(this));
    };

    return DB;

  })();

  exports.db = _db = new DB({});

  exports.DB = DB;

  _ref1 = DB.prototype;
  _fn = function(key) {
    return exports[key] = function() {
      var args;
      args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      return _db[key].apply(_db, args);
    };
  };
  for (k in _ref1) {
    v = _ref1[k];
    _fn(k);
  }

}).call(this);
