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


  /*
  @name         getFullTextFromJSKOSObject
  @description  This function generates the _fulltext-Object, which is required for search
                   Structure is documented here: https://docs.easydb.de/en/technical/plugins/customdatatype/#general-keys
  @param        {object}                JSKOS                 a jskos-object
  @param        {array}                 databaseLanguages     a list of easydb5-languages
  @return       {object}                returns _standard-Object
   */

  DANTEUtil.getFullTextFromJSKOSObject = function(object, databaseLanguages) {
    var _fulltext, arrayValue, arrayValueOfObject, fullTextString, i, j, k, key, l, l10nObject, l10nObjectKey, l10nObjectValue, l10nObjectWithShortenedLanguages, l10nObjectWithShortenedLanguagesKey, l10nObjectWithShortenedLanguagesValue, language, len, len1, len2, len3, objectKey, objectKeys, objectValue, prefLabelOfArrayKey, prefLabelOfArrayValue, propertyType, ref, ref1, ref2, shortenedDatabaseLanguages, shortenedLanguage, value;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getLanguageControl().getLanguages().slice();
    }
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    if (Array.isArray(object)) {
      object = object[0];
    }
    _fulltext = {};
    fullTextString = '';
    l10nObject = {};
    l10nObjectWithShortenedLanguages = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    for (j = 0, len1 = shortenedDatabaseLanguages.length; j < len1; j++) {
      language = shortenedDatabaseLanguages[j];
      l10nObjectWithShortenedLanguages[language] = '';
    }
    objectKeys = ['prefLabel', 'altLabel', 'hiddenLabel', 'identifier', 'notation', 'uri', 'scopeNote', 'definition', 'startDate', 'endDate', 'example', 'historyNote', 'note', 'changeNote', 'startPlace', 'endPlace'];
    for (key in object) {
      value = object[key];
      if (objectKeys.includes(key)) {
        propertyType = typeof value;
        if (propertyType === 'string') {
          fullTextString += value + ' ';
          for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
            l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
            l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + value + ' ';
          }
        }
        if (propertyType === 'object') {
          if (Array.isArray(object[key])) {
            ref = object[key];
            for (k = 0, len2 = ref.length; k < len2; k++) {
              arrayValue = ref[k];
              if (typeof arrayValue === 'string') {
                fullTextString += arrayValue + ' ';
                for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
                  l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
                  l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + arrayValue + ' ';
                }
              } else if (typeof arrayValue === 'object') {
                if (arrayValue != null ? arrayValue.prefLabel : void 0) {
                  ref1 = arrayValue.prefLabel;
                  for (prefLabelOfArrayKey in ref1) {
                    prefLabelOfArrayValue = ref1[prefLabelOfArrayKey];
                    fullTextString += prefLabelOfArrayValue + ' ';
                    for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
                      l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
                      l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + prefLabelOfArrayValue + ' ';
                    }
                  }
                }
              }
            }
          } else {
            ref2 = object[key];
            for (objectKey in ref2) {
              objectValue = ref2[objectKey];
              if (Array.isArray(objectValue)) {
                for (l = 0, len3 = objectValue.length; l < len3; l++) {
                  arrayValueOfObject = objectValue[l];
                  fullTextString += arrayValueOfObject + ' ';
                  if (l10nObjectWithShortenedLanguages.hasOwnProperty(objectKey)) {
                    l10nObjectWithShortenedLanguages[objectKey] += arrayValueOfObject + ' ';
                  }
                }
              }
              if (typeof objectValue === 'string') {
                fullTextString += objectValue + ' ';
                if (l10nObjectWithShortenedLanguages[objectKey]) {
                  l10nObjectWithShortenedLanguages[objectKey] += objectValue + ' ';
                }
              }
            }
          }
        }
      }
    }
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (l10nObjectWithShortenedLanguages[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = l10nObjectWithShortenedLanguages[shortenedLanguage];
      }
    }
    _fulltext.text = fullTextString;
    _fulltext.l10ntext = l10nObject;
    return _fulltext;
  };


  /*
  @name         getStandardFromJSKOSObject
  @description  This function generates the _standard-Object, which is required for display-purposes
                   Structure is documented here: https://docs.easydb.de/en/technical/plugins/customdatatype/#general-keys
  @param        {object}     JSKOS     a jskos-object
  @return       {object}              returns _standard-Object
   */

  DANTEUtil.getStandardFromJSKOSObject = function(JSKOS, databaseLanguages) {
    var _standard, hasl10n, i, l10nObject, l10nObjectKey, l10nObjectValue, language, len, shortenedDatabaseLanguages, shortenedLanguage;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getLanguageControl().getLanguages().slice();
    }
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    if (Array.isArray(JSKOS)) {
      JSKOS = JSKOS[0];
    }
    _standard = {};
    l10nObject = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    hasl10n = false;
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (JSKOS.prefLabel[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = JSKOS.prefLabel[shortenedLanguage];
        hasl10n = true;
      }
    }
    if (hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (l10nObject[l10nObjectKey] === '') {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel[Object.keys(JSKOS.prefLabel)[0]];
        }
      }
    }
    if (!hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (JSKOS.prefLabel['und']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['und'];
        } else if (JSKOS.prefLabel['zxx']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['zxx'];
        } else if (JSKOS.prefLabel['mis']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mis'];
        } else if (JSKOS.prefLabel['mul']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mul'];
        }
      }
    }
    _standard.l10ntext = l10nObject;
    return _standard;
  };


  /*
  @name         getFacetTermFromJSKOSObject
  @description  generates a json-structure, which is only used for facetting (aka filter) in frontend
   */

  DANTEUtil.getFacetTermFromJSKOSObject = function(JSKOS) {
    var _facet_term, databaseLanguages, hasl10n, i, l10nObject, l10nObjectKey, l10nObjectValue, language, len, shortenedDatabaseLanguages, shortenedLanguage;
    console.log("f:getFacetTermFromJSKOSObject");
    databaseLanguages = ez5.loca.getLanguageControl().getLanguages().slice();
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    if (Array.isArray(JSKOS)) {
      JSKOS = JSKOS[0];
    }
    _facet_term = {};
    l10nObject = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    hasl10n = false;
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (JSKOS.prefLabel[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = JSKOS.prefLabel[shortenedLanguage];
        l10nObject[l10nObjectKey] = l10nObject[l10nObjectKey] + '@$@' + JSKOS.uri;
        hasl10n = true;
      }
    }
    if (hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (l10nObject[l10nObjectKey] === '') {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel[Object.keys(JSKOS.prefLabel)[0]];
          l10nObject[l10nObjectKey] = l10nObject[l10nObjectKey] + '@$@' + JSKOS.uri;
        }
      }
    }
    if (!hasl10n) {
      for (l10nObjectKey in l10nObject) {
        l10nObjectValue = l10nObject[l10nObjectKey];
        if (JSKOS.prefLabel['und']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['und'];
        } else if (JSKOS.prefLabel['zxx']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['zxx'];
        } else if (JSKOS.prefLabel['mis']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mis'];
        } else if (JSKOS.prefLabel['mul']) {
          l10nObject[l10nObjectKey] = JSKOS.prefLabel['mul'];
        }
        l10nObject[l10nObjectKey] = l10nObject[l10nObjectKey] + '@$@' + JSKOS.uri;
      }
    }
    _facet_term = l10nObject;
    return _facet_term;
  };

  return DANTEUtil;

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

DANTEUpdate = (function() {
  function DANTEUpdate() {}

  DANTEUpdate.prototype.__start_update = function(arg) {
    var availabilityCheck_xhr, plugin_config, server_config, testURL;
    server_config = arg.server_config, plugin_config = arg.plugin_config;
    testURL = 'https://api.dante.gbv.de/testAPICalls';
    availabilityCheck_xhr = new CUI.XHR({
      url: testURL
    });
    return availabilityCheck_xhr.start().done(function(data, status, statusText) {
      if ((data != null ? data.status : void 0) === true) {
        return ez5.respondSuccess({
          state: {
            "start_update": new Date().toUTCString(),
            "databaseLanguages": server_config.base.system.languages.database,
            "default_language": server_config.base.system.update_interval_dante.default_language
          }
        });
      } else {
        return ez5.respondError("custom.data.type.dante.update.error.generic", {
          error: "Test on DANTE-API was not successfull!"
        });
      }
    });
  };

  DANTEUpdate.prototype.__updateData = function(arg) {
    var DANTEUri, DANTEUris, chunkWorkPromise, databaseLanguages, defaultLanguage, default_language, j, len, object, objects, objectsMap, objectsToUpdate, plugin_config, state, that;
    objects = arg.objects, plugin_config = arg.plugin_config, state = arg.state;
    that = this;
    objectsMap = {};
    DANTEUris = [];
    databaseLanguages = state.databaseLanguages;
    default_language = state.default_language;
    defaultLanguage = false;
    if (default_language) {
      if (typeof default_language === 'string' || default_language instanceof String) {
        if (default_language.length === 2) {
          defaultLanguage = default_language;
        }
      }
    }
    for (j = 0, len = objects.length; j < len; j++) {
      object = objects[j];
      if (!(object.identifier && object.data)) {
        continue;
      }
      DANTEUri = object.data.conceptURI;
      if (CUI.util.isEmpty(DANTEUri)) {
        continue;
      }
      if (!objectsMap[DANTEUri]) {
        objectsMap[DANTEUri] = [];
      }
      objectsMap[DANTEUri].push(object);
      DANTEUris.push(DANTEUri);
    }
    if (DANTEUris.length === 0) {
      return ez5.respondSuccess({
        payload: []
      });
    }
    DANTEUris = DANTEUris.filter((function(_this) {
      return function(x, i, a) {
        return a.indexOf(x) === i;
      };
    })(this));
    objectsToUpdate = [];
    chunkWorkPromise = CUI.chunkWork.call(this, {
      items: DANTEUris,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var deferred, extendedInfo_xhr, originalDANTEUri, uri;
          uri = items[0];
          originalDANTEUri = uri;
          uri = 'https://api.dante.gbv.de/data?cache=1&uri=' + CUI.encodeURIComponentNicely(uri) + '&properties=+ancestors,altLabel,hiddenLabel,notation,scopeNote,definition,identifier,example,startDate,endDate,startPlace,endPlace';
          deferred = new CUI.Deferred();
          extendedInfo_xhr = new CUI.XHR({
            url: uri
          });
          extendedInfo_xhr.start().done(function(data, status, statusText) {
            var ancestor, cdataFromObjectsMap, conceptAncestors, conceptAncestorsString, hasSurelyChanges, k, l, len1, len2, len3, m, objectsMapKey, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, resultsDANTEUri, updatedDANTEcdata, validFrontendLanguageGiven;
            if ((data != null ? data.length : void 0) === 1) {
              data = data[0];
              if (data != null ? data.prefLabel : void 0) {
                resultsDANTEUri = data.uri;
                ref = objectsMap[originalDANTEUri];
                for (objectsMapKey = k = 0, len1 = ref.length; k < len1; objectsMapKey = ++k) {
                  cdataFromObjectsMap = ref[objectsMapKey];
                  cdataFromObjectsMap = cdataFromObjectsMap.data;
                  updatedDANTEcdata = {};
                  updatedDANTEcdata.conceptURI = data.uri;
                  updatedDANTEcdata.conceptAncestors = '';
                  if ((data != null ? data.ancestors.length : void 0) > 0) {
                    conceptAncestors = [];
                    ref1 = data.ancestors;
                    for (l = 0, len2 = ref1.length; l < len2; l++) {
                      ancestor = ref1[l];
                      conceptAncestors.push(ancestor.uri);
                    }
                    if (conceptAncestors.length > 0) {
                      conceptAncestors.push(data.uri);
                      conceptAncestorsString = conceptAncestors.join(' ');
                      updatedDANTEcdata.conceptAncestors = conceptAncestorsString;
                    }
                  }
                  if ((cdataFromObjectsMap != null ? (ref2 = cdataFromObjectsMap.frontendLanguage) != null ? ref2.length : void 0 : void 0) === 2) {
                    updatedDANTEcdata.frontendLanguage = cdataFromObjectsMap.frontendLanguage;
                    if ((cdataFromObjectsMap != null ? cdataFromObjectsMap.conceptNameChosenByHand : void 0) === false || !cdataFromObjectsMap.hasOwnProperty('conceptNameChosenByHand')) {
                      updatedDANTEcdata.conceptNameChosenByHand = false;
                      if (data['prefLabel']) {
                        if (data['prefLabel'][cdataFromObjectsMap.frontendLanguage] || data['prefLabel']['zxx'] || data['prefLabel']['und'] || data['prefLabel']['mus'] || data['prefLabel']['mil']) {
                          if ((ref3 = data['prefLabel']) != null ? ref3[cdataFromObjectsMap.frontendLanguage] : void 0) {
                            updatedDANTEcdata.conceptName = data['prefLabel'][cdataFromObjectsMap.frontendLanguage];
                          } else if (data['prefLabel']['zxx']) {
                            updatedDANTEcdata.conceptName = data['prefLabel']['zxx'];
                          } else if (data['prefLabel']['und']) {
                            updatedDANTEcdata.conceptName = data['prefLabel']['und'];
                          } else if (data['prefLabel']['mis']) {
                            updatedDANTEcdata.conceptName = data['prefLabel']['mis'];
                          } else if (data['prefLabel']['mul']) {
                            updatedDANTEcdata.conceptName = data['prefLabel']['mul'];
                          }
                        }
                      }
                    }
                  }
                  if ((cdataFromObjectsMap != null ? cdataFromObjectsMap.conceptNameChosenByHand : void 0) === true) {
                    updatedDANTEcdata.conceptName = cdataFromObjectsMap.conceptName;
                    updatedDANTEcdata.conceptNameChosenByHand = true;
                  }
                  if (defaultLanguage) {
                    validFrontendLanguageGiven = false;
                    if (cdataFromObjectsMap != null ? cdataFromObjectsMap.frontendLanguage : void 0) {
                      if (cdataFromObjectsMap.frontendLanguage.length === 2) {
                        validFrontendLanguageGiven = true;
                      }
                    }
                    if (!validFrontendLanguageGiven) {
                      updatedDANTEcdata.frontendLanguage = defaultLanguage;
                    }
                  }
                  if (!(updatedDANTEcdata != null ? updatedDANTEcdata.conceptName : void 0)) {
                    if (defaultLanguage) {
                      if ((ref4 = data['prefLabel']) != null ? ref4[defaultLanguage] : void 0) {
                        updatedDANTEcdata.conceptName = data['prefLabel'][defaultLanguage];
                      } else {
                        if ((ref5 = data.prefLabel) != null ? ref5.de : void 0) {
                          updatedDANTEcdata.conceptName = data.prefLabel.de;
                        } else if ((ref6 = data.prefLabel) != null ? ref6.en : void 0) {
                          updatedDANTEcdata.conceptName = data.prefLabel.en;
                        } else {
                          updatedDANTEcdata.conceptName = data.prefLabel[Object.keys(data.prefLabel)[0]];
                        }
                      }
                    } else {
                      if ((ref7 = data.prefLabel) != null ? ref7.de : void 0) {
                        updatedDANTEcdata.conceptName = data.prefLabel.de;
                      } else if ((ref8 = data.prefLabel) != null ? ref8.en : void 0) {
                        updatedDANTEcdata.conceptName = data.prefLabel.en;
                      } else {
                        updatedDANTEcdata.conceptName = data.prefLabel[Object.keys(data.prefLabel)[0]];
                      }
                    }
                  }
                  updatedDANTEcdata._standard = ez5.DANTEUtil.getStandardFromJSKOSObject(data, databaseLanguages);
                  updatedDANTEcdata._fulltext = ez5.DANTEUtil.getFullTextFromJSKOSObject(data, databaseLanguages);
                  if (!that.__hasChanges(objectsMap[originalDANTEUri][objectsMapKey].data, updatedDANTEcdata)) {
                    continue;
                  } else {
                    objectsMap[originalDANTEUri][objectsMapKey].data = updatedDANTEcdata;
                    objectsToUpdate.push(objectsMap[originalDANTEUri][objectsMapKey]);
                  }
                }
              }
            } else {
              if ((data != null ? data.length : void 0) === 0) {
                ref9 = objectsMap[originalDANTEUri];
                for (objectsMapKey = m = 0, len3 = ref9.length; m < len3; objectsMapKey = ++m) {
                  cdataFromObjectsMap = ref9[objectsMapKey];
                  cdataFromObjectsMap = cdataFromObjectsMap.data;
                  hasSurelyChanges = false;
                  updatedDANTEcdata = cdataFromObjectsMap;
                  if (updatedDANTEcdata != null ? updatedDANTEcdata.conceptAncestors : void 0) {
                    if (Array.isArray(updatedDANTEcdata.conceptAncestors)) {
                      updatedDANTEcdata.conceptAncestors = updatedDANTEcdata.conceptAncestors.join(' ');
                      hasSurelyChanges = true;
                    }
                  } else {
                    updatedDANTEcdata.conceptAncestors = '';
                    hasSurelyChanges = true;
                  }
                  if (!that.__hasChanges(objectsMap[originalDANTEUri][objectsMapKey].data, updatedDANTEcdata) && !hasSurelyChanges) {
                    continue;
                  } else {
                    objectsMap[originalDANTEUri][objectsMapKey].data = updatedDANTEcdata;
                    objectsToUpdate.push(objectsMap[originalDANTEUri][objectsMapKey]);
                  }
                }
              }
            }
            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.dante.update.error.generic", {
          error: "Error connecting to DANTE"
        });
      };
    })(this));
  };

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

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

  return DANTEUpdate;

})();

module.exports = new DANTEUpdate();
