// 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();
