// Generated by CoffeeScript 1.12.7
var GVKUpdate;

GVKUpdate = (function() {
  function GVKUpdate() {}

  GVKUpdate.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()
      }
    });
  };

  GVKUpdate.prototype.__updateData = function(arg) {
    var GVKIds, chunkWorkPromise, gvkID, gvkURI, j, len, object, objects, objectsMap, objectsToUpdate, plugin_config, that;
    objects = arg.objects, plugin_config = arg.plugin_config;
    that = this;
    objectsMap = {};
    GVKIds = [];
    for (j = 0, len = objects.length; j < len; j++) {
      object = objects[j];
      if (!(object.identifier && object.data)) {
        continue;
      }
      gvkURI = object.data.conceptURI;
      if (!gvkURI) {
        console.error("GVK-URI " + gvkURI + " is empty!?");
        continue;
      }
      gvkID = gvkURI.split('/');
      gvkID = gvkID.pop();
      gvkID = gvkID.replace('gvk:ppn:', '');
      if (CUI.util.isEmpty(gvkID)) {
        continue;
      }
      if (!objectsMap[gvkID]) {
        objectsMap[gvkID] = [];
      }
      objectsMap[gvkID].push(object);
      GVKIds.push(gvkID);
    }
    if (GVKIds.length === 0) {
      return ez5.respondSuccess({
        payload: []
      });
    }
    GVKIds = GVKIds.filter((function(_this) {
      return function(x, i, a) {
        return a.indexOf(x) === i;
      };
    })(this));
    objectsToUpdate = [];
    chunkWorkPromise = CUI.chunkWork.call(this, {
      items: GVKIds,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var GVKId, deferred, extendedInfo_xhr, xurl;
          GVKId = items[0];
          xurl = 'https://ws.gbv.de/suggest/csl2/?query=pica.ppn=' + GVKId + '&citationstyle=ieee&language=de&count=1';
          deferred = new CUI.Deferred();
          extendedInfo_xhr = new CUI.XHR({
            url: xurl
          });
          extendedInfo_xhr.start().done(function(data, status, statusText) {
            var k, len1, objectsMapEntry, ref, resultsGVKID, updatedGVKcdata;
            if (data[1].length === 1) {
              gvkURI = data[3][0];
              gvkID = gvkURI.split('/');
              gvkID = gvkID.pop();
              gvkID = gvkID.replace('gvk:ppn:', '');
              resultsGVKID = gvkID;
              updatedGVKcdata = {};
              updatedGVKcdata.conceptURI = gvkURI;
              updatedGVKcdata.conceptName = data[1][0];
              updatedGVKcdata._standard = {
                text: updatedGVKcdata.conceptName
              };
              updatedGVKcdata._fulltext = {
                string: updatedGVKcdata.conceptName + ' ' + gvkURI + ' ' + gvkID
              };
              if (!objectsMap[resultsGVKID]) {
                console.error("GVK nicht in objectsMap: " + resultsGVKID);
                console.error("da hat sich die PPN von " + GVKId + " zu " + resultsGVKID + " geändert");
              }
              ref = objectsMap[GVKId];
              for (k = 0, len1 = ref.length; k < len1; k++) {
                objectsMapEntry = ref[k];
                if (!that.__hasChanges(objectsMapEntry.data, updatedGVKcdata)) {
                  continue;
                }
                objectsMapEntry.data = updatedGVKcdata;
                objectsToUpdate.push(objectsMapEntry);
              }
            }
            return deferred.resolve();
          }).fail(function() {
            return deferred.reject();
          });
          return deferred.promise();
        };
      })(this)
    });
    return chunkWorkPromise.done((function(_this) {
      return function() {
        return ez5.respondSuccess({
          payload: objectsToUpdate
        });
      };
    })(this)).fail((function(_this) {
      return function() {
        return ez5.respondError("custom.data.type.gvk.update.error.generic", {
          error: "Error connecting to GVK-API"
        });
      };
    })(this));
  };

  GVKUpdate.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;
  };

  GVKUpdate.prototype.main = function(data) {
    var j, key, len, ref;
    if (!data) {
      ez5.respondError("custom.data.type.gvk.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.gvk.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.gvk.update.error.objects-missing");
        return;
      }
      if (!(data.objects instanceof Array)) {
        ez5.respondError("custom.data.type.gvk.update.error.objects-not-array");
        return;
      }
      if (!data.state) {
        ez5.respondError("custom.data.type.gvk.update.error.state-missing");
        return;
      }
      if (!data.batch_info) {
        ez5.respondError("custom.data.type.gvk.update.error.batch_info-missing");
        return;
      }
      this.__updateData(data);
    } else {
      return ez5.respondError("custom.data.type.gvk.update.error.invalid-action", {
        action: data.action
      });
    }
  };

  return GVKUpdate;

})();

module.exports = new GVKUpdate();
