// Generated by CoffeeScript 1.12.7
ez5.GNDUtil = (function() {
  function GNDUtil() {}

  GNDUtil.getFullTextFromEntityFactsJSON = function(efJSON) {
    var _fulltext, entry, i, i1, j, j1, k, k1, l, l1, len, len1, len10, len11, len12, len13, len14, len15, len16, len17, len18, len19, len2, len20, len21, len22, len23, len24, len25, len26, len27, len28, len29, len3, len4, len5, len6, len7, len8, len9, m, m1, n, n1, o, o1, p, p1, q, q1, r, r1, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref19, ref2, ref20, ref21, ref22, ref23, ref24, ref25, ref26, ref27, ref28, ref29, ref3, ref4, ref5, ref6, ref7, ref8, ref9, s, s1, t, t1, u, v, w, x, y, z;
    _fulltext = '';
    _fulltext += efJSON['id'] + ' ';
    _fulltext = efJSON['gndIdentifier'] + ' ';
    if (efJSON != null ? efJSON.oldAuthorityNumber : void 0) {
      ref = efJSON.oldAuthorityNumber;
      for (i = 0, len = ref.length; i < len; i++) {
        entry = ref[i];
        _fulltext += entry + ' ';
      }
    }
    if (efJSON != null ? efJSON.gndSubjectCategory : void 0) {
      ref1 = efJSON.gndSubjectCategory;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        entry = ref1[j];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    _fulltext += efJSON['preferredName'] + ' ';
    if (efJSON != null ? efJSON.variantName : void 0) {
      ref2 = efJSON.variantName;
      for (k = 0, len2 = ref2.length; k < len2; k++) {
        entry = ref2[k];
        _fulltext += entry + ' ';
      }
    }
    if (efJSON != null ? efJSON.biographicalOrHistoricalInformation : void 0) {
      ref3 = efJSON.biographicalOrHistoricalInformation;
      for (l = 0, len3 = ref3.length; l < len3; l++) {
        entry = ref3[l];
        _fulltext += entry + ' ';
      }
    }
    if (efJSON != null ? efJSON.dateOfEstablishment : void 0) {
      ref4 = efJSON.dateOfEstablishment;
      for (m = 0, len4 = ref4.length; m < len4; m++) {
        entry = ref4[m];
        _fulltext += entry + ' ';
      }
    }
    if (efJSON != null ? efJSON.dateOfPublication : void 0) {
      ref5 = efJSON.dateOfPublication;
      for (n = 0, len5 = ref5.length; n < len5; n++) {
        entry = ref5[n];
        _fulltext += entry + ' ';
      }
    }
    if (efJSON != null ? efJSON.dateOfBirth : void 0) {
      _fulltext += efJSON.dateOfBirth + ' ';
    }
    if (efJSON != null ? efJSON.dateOfProduction : void 0) {
      _fulltext += efJSON.dateOfProduction + ' ';
    }
    if (efJSON != null ? efJSON.dateOfDeath : void 0) {
      _fulltext += efJSON.dateOfDeath + ' ';
    }
    if (efJSON != null ? efJSON.dateOfTermination : void 0) {
      _fulltext += efJSON.dateOfTermination + ' ';
    }
    if (efJSON != null ? efJSON.author : void 0) {
      ref6 = efJSON.author;
      for (o = 0, len6 = ref6.length; o < len6; o++) {
        entry = ref6[o];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.firstAuthor : void 0) {
      ref7 = efJSON.firstAuthor;
      for (p = 0, len7 = ref7.length; p < len7; p++) {
        entry = ref7[p];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.organizerOrHost : void 0) {
      ref8 = efJSON.organizerOrHost;
      for (q = 0, len8 = ref8.length; q < len8; q++) {
        entry = ref8[q];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.gender : void 0) {
      ref9 = efJSON.gender;
      for (r = 0, len9 = ref9.length; r < len9; r++) {
        entry = ref9[r];
        if (entry.label) {
          _fulltext += entry.label + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.placeOfEvent : void 0) {
      ref10 = efJSON.placeOfEvent;
      for (s = 0, len10 = ref10.length; s < len10; s++) {
        entry = ref10[s];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.placeOfBirth : void 0) {
      ref11 = efJSON.placeOfBirth;
      for (t = 0, len11 = ref11.length; t < len11; t++) {
        entry = ref11[t];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.placeOfDeath : void 0) {
      ref12 = efJSON.placeOfDeath;
      for (u = 0, len12 = ref12.length; u < len12; u++) {
        entry = ref12[u];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.placeOfBusiness : void 0) {
      ref13 = efJSON.placeOfBusiness;
      for (v = 0, len13 = ref13.length; v < len13; v++) {
        entry = ref13[v];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.associatedPlace : void 0) {
      ref14 = efJSON.associatedPlace;
      for (w = 0, len14 = ref14.length; w < len14; w++) {
        entry = ref14[w];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.topic : void 0) {
      ref15 = efJSON.topic;
      for (x = 0, len15 = ref15.length; x < len15; x++) {
        entry = ref15[x];
        if (entry.label) {
          _fulltext += entry.label + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.predecessor : void 0) {
      ref16 = efJSON.predecessor;
      for (y = 0, len16 = ref16.length; y < len16; y++) {
        entry = ref16[y];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.precedingCorporateBody : void 0) {
      ref17 = efJSON.precedingCorporateBody;
      for (z = 0, len17 = ref17.length; z < len17; z++) {
        entry = ref17[z];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.isA : void 0) {
      ref18 = efJSON.isA;
      for (i1 = 0, len18 = ref18.length; i1 < len18; i1++) {
        entry = ref18[i1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.composer : void 0) {
      ref19 = efJSON.composer;
      for (j1 = 0, len19 = ref19.length; j1 < len19; j1++) {
        entry = ref19[j1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.relatedWork : void 0) {
      ref20 = efJSON.relatedWork;
      for (k1 = 0, len20 = ref20.length; k1 < len20; k1++) {
        entry = ref20[k1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.relatedPerson : void 0) {
      ref21 = efJSON.relatedPerson;
      for (l1 = 0, len21 = ref21.length; l1 < len21; l1++) {
        entry = ref21[l1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.precedingPlaceOrGeographicName : void 0) {
      ref22 = efJSON.precedingPlaceOrGeographicName;
      for (m1 = 0, len22 = ref22.length; m1 < len22; m1++) {
        entry = ref22[m1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.hierarchicalSuperiorOfTheCorporateBody : void 0) {
      ref23 = efJSON.hierarchicalSuperiorOfTheCorporateBody;
      for (n1 = 0, len23 = ref23.length; n1 < len23; n1++) {
        entry = ref23[n1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.broaderTermInstantial : void 0) {
      ref24 = efJSON.broaderTermInstantial;
      for (o1 = 0, len24 = ref24.length; o1 < len24; o1++) {
        entry = ref24[o1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.broaderTermGeneral : void 0) {
      ref25 = efJSON.broaderTermGeneral;
      for (p1 = 0, len25 = ref25.length; p1 < len25; p1++) {
        entry = ref25[p1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.professionOrOccupation : void 0) {
      ref26 = efJSON.professionOrOccupation;
      for (q1 = 0, len26 = ref26.length; q1 < len26; q1++) {
        entry = ref26[q1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.architect : void 0) {
      ref27 = efJSON.architect;
      for (r1 = 0, len27 = ref27.length; r1 < len27; r1++) {
        entry = ref27[r1];
        if (entry.preferredName) {
          _fulltext += entry.preferredName + ' ';
        }
      }
    }
    if (efJSON != null ? efJSON.opusNumericDesignationOfMusicalWork : void 0) {
      ref28 = efJSON.opusNumericDesignationOfMusicalWork;
      for (s1 = 0, len28 = ref28.length; s1 < len28; s1++) {
        entry = ref28[s1];
        _fulltext += entry + ' ';
      }
    }
    if (efJSON != null ? efJSON.definition : void 0) {
      ref29 = efJSON.definition;
      for (t1 = 0, len29 = ref29.length; t1 < len29; t1++) {
        entry = ref29[t1];
        _fulltext += entry + ' ';
      }
    }
    return _fulltext;
  };

  return GNDUtil;

})();
// Generated by CoffeeScript 1.12.7
var GNDUpdate;

GNDUpdate = (function() {
  function GNDUpdate() {}

  GNDUpdate.prototype.__start_update = function(arg) {
    var plugin_config, server_config;
    server_config = arg.server_config, plugin_config = arg.plugin_config;
    return ez5.respondSuccess({
      state: {
        "start_update": new Date().toUTCString()
      }
    });
  };

  GNDUpdate.prototype.__updateData = function(arg) {
    var GNDId, GNDIds, deferred, fn, gndID, gndURI, j, k, key, l, len, len1, len2, object, objects, objectsMap, objectsToUpdate, plugin_config, ref, that, timeout, xhrPromises;
    objects = arg.objects, plugin_config = arg.plugin_config;
    that = this;
    objectsMap = {};
    GNDIds = [];
    for (j = 0, len = objects.length; j < len; j++) {
      object = objects[j];
      if (!(object.identifier && object.data)) {
        continue;
      }
      gndURI = object.data.conceptURI;
      gndID = gndURI.split('d-nb.info/gnd/');
      gndID = gndID[1];
      if (CUI.util.isEmpty(gndID)) {
        continue;
      }
      if (!objectsMap[gndID]) {
        objectsMap[gndID] = [];
      }
      objectsMap[gndID].push(object);
      GNDIds.push(gndID);
    }
    if (GNDIds.length === 0) {
      return ez5.respondSuccess({
        payload: []
      });
    }
    timeout = ((ref = plugin_config.update) != null ? ref.timeout : void 0) || 0;
    timeout *= 1000;
    GNDIds = GNDIds.filter((function(_this) {
      return function(x, i, a) {
        return a.indexOf(x) === i;
      };
    })(this));
    objectsToUpdate = [];
    xhrPromises = [];
    for (key = k = 0, len1 = GNDIds.length; k < len1; key = ++k) {
      GNDId = GNDIds[key];
      deferred = new CUI.Deferred();
      xhrPromises.push(deferred);
    }
    console.error("GNDIds ", GNDIds);
    fn = function(key, GNDId) {
      var growingTimeout, xurl;
      xurl = 'https://jsontojsonp.gbv.de/?url=' + CUI.encodeURIComponentNicely('https://lobid.org/gnd/' + GNDId);
      console.error("calling " + xurl);
      growingTimeout = key * 100;
      return setTimeout((function() {
        var extendedInfo_xhr;
        extendedInfo_xhr = new CUI.XHR({
          url: xurl
        });
        return extendedInfo_xhr.start().done(function(data, status, statusText) {
          var len3, m, objectsMapEntry, ref1, results, resultsGNDID, updatedGNDcdata;
          if (!data.preferredName) {
            console.error("Record https://d-nb.info/gnd/" + gndID + " not supported in lobid.org somehow");
            return console.error(data);
          } else {
            resultsGNDID = data['gndIdentifier'];
            updatedGNDcdata = {};
            updatedGNDcdata.conceptURI = data['id'];
            updatedGNDcdata.conceptName = data['preferredName'];
            updatedGNDcdata._standard = {
              text: updatedGNDcdata.conceptName
            };
            updatedGNDcdata._fulltext = {
              string: ez5.GNDUtil.getFullTextFromEntityFactsJSON(data),
              text: ez5.GNDUtil.getFullTextFromEntityFactsJSON(data)
            };
            if (!objectsMap[resultsGNDID]) {
              console.error("GND nicht in objectsMap: " + resultsGNDID);
              console.error("da hat sich die ID von " + GNDId + " zu " + resultsGNDID + " geändert");
            }
            ref1 = objectsMap[GNDId];
            results = [];
            for (m = 0, len3 = ref1.length; m < len3; m++) {
              objectsMapEntry = ref1[m];
              if (!that.__hasChanges(objectsMapEntry.data, updatedGNDcdata)) {
                continue;
              }
              objectsMapEntry.data = updatedGNDcdata;
              results.push(objectsToUpdate.push(objectsMapEntry));
            }
            return results;
          }
        }).fail((function(data, status, statusText) {
          return ez5.respondError("custom.data.type.gnd.update.error.generic", {
            searchQuery: searchQuery,
            error: e + "Error connecting to entityfacts"
          });
        })).always((function(_this) {
          return function() {
            xhrPromises[key].resolve();
            return xhrPromises[key].promise();
          };
        })(this));
      }), growingTimeout);
    };
    for (key = l = 0, len2 = GNDIds.length; l < len2; key = ++l) {
      GNDId = GNDIds[key];
      fn(key, GNDId);
    }
    return CUI.whenAll(xhrPromises).done((function(_this) {
      return function() {
        return ez5.respondSuccess({
          payload: objectsToUpdate
        });
      };
    })(this));
  };

  GNDUpdate.prototype.__hasChanges = function(objectOne, objectTwo) {
    var j, key, len, ref;
    ref = ["conceptName", "conceptURI", "_standard", "_fulltext"];
    for (j = 0, len = ref.length; j < len; j++) {
      key = ref[j];
      if (!CUI.util.isEqual(objectOne[key], objectTwo[key])) {
        return true;
      }
    }
    return false;
  };

  GNDUpdate.prototype.main = function(data) {
    var j, key, len, ref;
    if (!data) {
      ez5.respondError("custom.data.type.gnd.update.error.payload-missing");
      return;
    }
    ref = ["action", "server_config", "plugin_config"];
    for (j = 0, len = ref.length; j < len; j++) {
      key = ref[j];
      if (!data[key]) {
        ez5.respondError("custom.data.type.gnd.update.error.payload-key-missing", {
          key: key
        });
        return;
      }
    }
    if (data.action === "start_update") {
      this.__start_update(data);
    } else if (data.action === "update") {
      if (!data.objects) {
        ez5.respondError("custom.data.type.gnd.update.error.objects-missing");
        return;
      }
      if (!(data.objects instanceof Array)) {
        ez5.respondError("custom.data.type.gnd.update.error.objects-not-array");
        return;
      }
      if (!data.state) {
        ez5.respondError("custom.data.type.gnd.update.error.state-missing");
        return;
      }
      if (!data.batch_info) {
        ez5.respondError("custom.data.type.gnd.update.error.batch_info-missing");
        return;
      }
      this.__updateData(data);
    } else {
      return ez5.respondError("custom.data.type.gnd.update.error.invalid-action", {
        action: data.action
      });
    }
  };

  return GNDUpdate;

})();

module.exports = new GNDUpdate();
