// Generated by CoffeeScript 1.12.7
var RemoteEasydb,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

RemoteEasydb = (function(superClass) {
  extend(RemoteEasydb, superClass);

  function RemoteEasydb() {
    return RemoteEasydb.__super__.constructor.apply(this, arguments);
  }

  RemoteEasydb.prototype.initOpts = function() {
    RemoteEasydb.__super__.initOpts.call(this);
    return this.addOpts({
      easydb: {
        check: {
          idx: {
            mandatory: true,
            check: "Integer"
          },
          active: {
            mandatory: true,
            check: Boolean
          },
          url: {
            mandatory: true,
            check: String
          },
          name: {
            check: String
          },
          version: {
            check: String,
            "default": ""
          },
          token: {
            check: String
          },
          error: {
            check: "PlainObject",
            "default": {}
          }
        }
      }
    });
  };

  RemoteEasydb.prototype.readOpts = function() {
    RemoteEasydb.__super__.readOpts.call(this);
    this.__schema = {};
    this.__session = null;
    this.user_keys = {};
    this.__lastError = null;
  };

  RemoteEasydb.prototype.isFylr = function() {
    if (CUI.util.isEmpty(this._easydb.version)) {
      return false;
    }
    return parseFloat(this._easydb.version.replace("v", "")) >= 6.0;
  };

  RemoteEasydb.prototype.hasTags = function() {
    return this.__tags && !CUI.util.isEmpty(this.__tags);
  };

  RemoteEasydb.prototype.getEasydb4Info = function() {
    var baseConfig, easydb4, easydb_id, networkMap, objecttype, ref, ref1, ref2, ref3, ref4, ref5, table_id, table_name, table_ref_col, target, x;
    networkMap = {
      "uni-bern": {
        easydb_id: "10"
      },
      "easydb5.kunsthist.unibas.ch": {
        easydb_id: "11"
      },
      "easydb.fu-berlin.de": {
        easydb_id: "12"
      },
      "portal.digitale-diathek.net": {
        easydb_id: "13"
      },
      "khistmediathek.uzh.ch": {
        easydb_id: "14"
      },
      "unidam1.univie.ac.at": {
        easydb_id: "21",
        table_id: "39",
        table_ref_col: "easydb_4_id"
      },
      "fotomarburg.digitale-diathek.net": {
        easydb_id: "22"
      },
      "freikon.uni-freiburg.de": {
        easydb_id: "31"
      },
      "dpl.uni-stuttgart.de": {
        easydb_id: "34"
      },
      "bilddatenbank.uni-rostock.de": {
        easydb_id: "39",
        table_id: "39"
      },
      "goepix.uni-goettingen": {
        easydb_id: "73",
        table_name: "bilder"
      },
      "fylr.burg-halle.de": {
        easydb_id: "76",
        table_name: "bilder"
      },
      "mmz-easydb.rz.uni-jena.de": {
        easydb_id: "81",
        table_name: "bilder"
      },
      "udk-berlin.de": {
        easydb_id: "85",
        table_name: "bilder"
      },
      "researchbase-2.uni-muenster.de": {
        easydb_id: "90",
        table_name: "bilder",
        table_ref_col: "easydb4_id"
      },
      "ml-s-fylr-1.rrz.uni-hamburg.de": {
        easydb_id: "95"
      }
    };
    ref = Object.entries(networkMap);
    for (x of ref) {
      target = x[0], (ref1 = x[1], easydb_id = ref1.easydb_id, table_id = (ref2 = ref1.table_id) != null ? ref2 : "01", table_name = (ref3 = ref1.table_name) != null ? ref3 : "Bilder", objecttype = (ref4 = ref1.objecttype) != null ? ref4 : "bilder", table_ref_col = (ref5 = ref1.table_ref_col) != null ? ref5 : "easydb4_reference");
      if (this._easydb.url.includes(target)) {
        return {
          easydb_id: easydb_id,
          table_id: table_id,
          table_name: table_name,
          objecttype: objecttype,
          table_ref_col: table_ref_col
        };
      }
    }
    baseConfig = ez5.session.getBaseConfig("plugin", "easydb-connector-plugin");
    baseConfig = baseConfig.system || baseConfig;
    easydb4 = baseConfig.connector_easydb4 || null;
    if (easydb4) {
      console.info("Remote easydb '" + this.getDisplayname() + "' has easydb 4 configuration: ", easydb4);
    } else {
      console.warn("Remote easydb '" + this.getDisplayname() + "' contains no easydb 4 configuration.");
    }
    return easydb4;
  };

  RemoteEasydb.prototype.getServerUrl = function() {
    return this._easydb.url;
  };

  RemoteEasydb.prototype.getServerToken = function() {
    return this.__session.token;
  };

  RemoteEasydb.prototype.getSession = function() {
    return this.__session;
  };

  RemoteEasydb.prototype.getInstance = function() {
    return this.__instance;
  };

  RemoteEasydb.prototype.addTokenToUrl = function(url) {
    if (!url) {
      return url;
    }
    if (url.indexOf("?") > -1) {
      return url + "&access_token=" + this.__session.token;
    } else {
      return url + "?access_token=" + this.__session.token;
    }
  };

  RemoteEasydb.prototype.getExportVersionGroups = function() {
    return Asset.getExportVersionGroups(this.__session.getEASConfig());
  };

  RemoteEasydb.prototype.getDisplayname = function() {
    return this._easydb.name;
  };

  RemoteEasydb.prototype.isActive = function() {
    return this._easydb.active;
  };

  RemoteEasydb.prototype.isReachable = function() {
    return !!this.__instance;
  };

  RemoteEasydb.prototype.getLastError = function() {
    return this.__lastError;
  };

  RemoteEasydb.prototype.load = function() {
    var dfr, loc;
    dfr = new CUI.Deferred();
    dfr.fail((function(_this) {
      return function(loca_key, loca_key_attrs) {
        var err;
        if (loca_key_attrs == null) {
          loca_key_attrs = {};
        }
        err = loca_key != null ? loca_key.responseJSON : void 0;
        if (err) {
          loca_key_attrs = err.parameters;
          loca_key = err.code;
        }
        _this.__instance = null;
        if (CUI.util.isString(loca_key)) {
          _this.__lastError = $$(loca_key, loca_key_attrs);
        } else {
          _this.__lastError = $$("remote.easydb.connect.unknown_error");
        }
      };
    })(this));
    dfr.done((function(_this) {
      return function() {
        return _this.__lastError = null;
      };
    })(this));
    if (!CUI.util.isEmptyObject(this._easydb.error)) {
      if (this._easydb.error.code) {
        return dfr.reject(this._easydb.error.code, this._easydb.error.parameters);
      } else {
        this.__lastError = this._easydb.error.msg;
        return CUI.rejectedPromise();
      }
    }
    if (this._easydb.url.startsWith("https://") || this._easydb.url.startsWith("http://")) {
      loc = CUI.parseLocation(this._easydb.url);
    } else {
      loc = null;
    }
    if (!loc) {
      console.warn("Remote easydb has an invalid url: ", this._easydb.url);
      dfr.reject("remote.easydb.connect.invalid_url", {
        url: this._easydb.url
      });
      return dfr.promise();
    }
    this.__session = new Session({
      remoteEasydb: this
    });
    this.__session.get(this._easydb.token).fail(dfr.reject).done((function(_this) {
      return function() {
        var l10nDeferred, l10nPromise, login_event, settingsPromise, tagsPromise;
        if (_this.__session.pendingTasks.length > 0) {
          console.warn("Remote easydb has pending tasks. This is currently not supported.", _this._easydb);
          dfr.reject("remote.easydb.connect.pending_tasks");
          return;
        }
        if (!_this.__session.hasSystemRight("root", "plugin.easydb-connector-plugin.allow_use_as_server")) {
          dfr.reject("remote.easydb.connect.no_right_to_use");
          return;
        }
        login_event = {
          type: "CONNECTOR_LOGIN",
          pollable: false,
          info: Connector.getSessionInfoForEvent()
        };
        _this.__instance = _this.__session.getInstance().name;
        settingsPromise = ez5.api.settings({
          timeout: 15000,
          remoteEasydb: _this,
          handle_error: function() {
            return true;
          }
        }).fail(function(xhr, status) {
          return _this.tellProblem(status);
        }).done(function(settings) {
          _this.setEasydbVersion(settings.version);
        });
        tagsPromise = ez5.api.tags({
          remoteEasydb: _this,
          withCredentials: true
        }).done(function(data) {
          var _tag, i, j, len, len1, ref, ref1, tagGroup;
          if (CUI.util.isEmpty(data)) {
            return;
          }
          for (i = 0, len = data.length; i < len; i++) {
            tagGroup = data[i];
            ref = tagGroup._tags;
            for (j = 0, len1 = ref.length; j < len1; j++) {
              _tag = ref[j];
              if (!((ref1 = _tag.tag) != null ? ref1._id : void 0)) {
                continue;
              }
              _tag.tag._id += "@" + _this.__instance;
            }
          }
          _this.__tags = data;
          ez5.tagForm.addTagGroupsFromData(data);
        });
        l10nDeferred = new CUI.Deferred();
        ez5.api.l10n({
          remoteEasydb: _this,
          withCredentials: true,
          api: "/user/CURRENT"
        }).fail(l10nDeferred.reject).done(function(data) {
          ez5.loca.set_user_keys.call(_this, 'CURRENT', data);
          EventPoller.saveEvent(login_event, _this, true).fail(function() {
            if (typeof _this.isFylr === "function" ? _this.isFylr() : void 0) {
              l10nDeferred.reject();
              _this.__lastError = $$("remote.easydb.connect.remote_connector_not_available");
              return;
            }
            return _this.__session.deauthenticate().always(function() {
              l10nDeferred.reject();
              _this.__lastError = $$("remote.easydb.connect.remote_connector_not_available");
            });
          }).done(function() {
            return l10nDeferred.resolve();
          });
        });
        l10nPromise = l10nDeferred.promise();
        CUI.whenAllReject(l10nPromise, tagsPromise, settingsPromise).done(dfr.resolve).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  RemoteEasydb.prototype.logout = function() {
    var dfr, info, logout_event, ref;
    if (!((ref = this.__session) != null ? ref.isAuthenticated() : void 0)) {
      return CUI.resolvedPromise();
    }
    info = Connector.getSessionInfoForEvent();
    info.duration = ez5.format_seconds(this.__session.getDuration() / 1000);
    logout_event = {
      type: "CONNECTOR_LOGOUT",
      pollable: false,
      info: info
    };
    dfr = new CUI.Deferred();
    EventPoller.saveEvent(logout_event, this, true).always((function(_this) {
      return function() {
        if (typeof _this.isFylr === "function" ? _this.isFylr() : void 0) {
          dfr.resolve();
          return;
        }
        return _this.__session.deauthenticate().done(dfr.resolve).fail(dfr.reject);
      };
    })(this));
    return dfr.promise();
  };

  RemoteEasydb.prototype.loadSchema = function() {
    this.__schema_inst = new Schema({
      remoteEasydb: this
    });
    this.__schema = {};
    return this.__schema_inst.load(null, this.__schema, ["CURRENT"], ["mask", "schema"]).done((function(_this) {
      return function() {
        _this.mask = {
          CURRENT: _this.__schema.mask.CURRENT
        };
        _this.schema = {
          CURRENT: _this.__schema.schema.CURRENT
        };
        ez5.bind_schema_funcs(_this.schema);
        _this.setInstanceInMaskAndSchema();
        _this.schema.enrich_schema(_this.schema.CURRENT, 'CURRENT');
        _this.schema.enrich_mask_schema(_this.mask.CURRENT, 'CURRENT');
        return _this.__schema_inst.initPreferredMask('CURRENT', _this.__schema);
      };
    })(this));
  };

  RemoteEasydb.prototype.get_user_key_CURRENT = function(key) {
    var ref;
    return (ref = this.user_keys.CURRENT) != null ? ref[key] : void 0;
  };

  RemoteEasydb.prototype.setInstanceInMaskAndSchema = function() {
    var col, i, j, k, len, len1, len2, mask, ref, ref1, ref2, set_ids_in_mask, table;
    set_ids_in_mask = (function(_this) {
      return function(mask) {
        var field, i, len, ref, results;
        mask._instance = _this.__instance;
        if (mask.mask_id) {
          mask.mask_id = mask.mask_id + '@' + _this.__instance;
        }
        if (mask.name) {
          mask.name = mask.name + '@' + _this.__instance;
        }
        if (mask.table_id) {
          mask.table_id = mask.table_id + '@' + _this.__instance;
        }
        ref = mask.fields;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          field = ref[i];
          if (field.other_table_id) {
            field.other_table_id = field.other_table_id + '@' + _this.__instance;
          }
          if (field.mask_id && field.mask_id !== 'PREFERRED') {
            field.mask_id = field.mask_id + '@' + _this.__instance;
          }
          if (field.mask) {
            results.push(set_ids_in_mask(field.mask));
          } else {
            results.push(void 0);
          }
        }
        return results;
      };
    })(this);
    ref = this.mask.CURRENT.masks;
    for (i = 0, len = ref.length; i < len; i++) {
      mask = ref[i];
      set_ids_in_mask(mask);
    }
    ref1 = this.schema.CURRENT.tables;
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      table = ref1[j];
      table.table_id = table.table_id + '@' + this.__instance;
      table.name = table.name + '@' + this.__instance;
      table._instance = this.__instance;
      ref2 = table.columns;
      for (k = 0, len2 = ref2.length; k < len2; k++) {
        col = ref2[k];
        if (col.other_table_id) {
          col.other_table_id = col.other_table_id + '@' + this.__instance;
        }
      }
    }
  };

  RemoteEasydb.prototype.setEasydbVersion = function(version) {
    this.__easydbVersion = version;
  };

  RemoteEasydb.prototype.version = function(exp_version) {
    var i, idx, len, part_exp, parts_exp, parts_v, v;
    v = this.__easydbVersion;
    if (v) {
      v = v.replace(/^v/, "");
    }
    if (CUI.util.isEmpty(exp_version)) {
      return v;
    }
    if (v === null) {
      return false;
    }
    parts_v = v.split(".").map((function(_this) {
      return function(v) {
        return parseInt(v);
      };
    })(this));
    parts_exp = exp_version.split(".").map((function(_this) {
      return function(v) {
        return parseInt(v);
      };
    })(this));
    for (idx = i = 0, len = parts_exp.length; i < len; idx = ++i) {
      part_exp = parts_exp[idx];
      if (parts_v[idx] > part_exp) {
        return true;
      }
      if (part_exp > parts_v[idx]) {
        return false;
      }
    }
    return true;
  };

  return RemoteEasydb;

})(CUI.Element);
