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

  IconclassUtil.getPreview = function(data, language) {
    var html, key, keywords, keywordsString, prefLabel, ref, ref1, ref2, ref3, that, val, xuri;
    that = this;
    html = '';
    if (data instanceof Array) {
      data = data[0];
    }
    if (!(data != null ? data.n : void 0)) {
      return false;
    }
    if (data != null ? data.txt[language] : void 0) {
      prefLabel = data != null ? data.txt[language] : void 0;
    } else {
      prefLabel = data != null ? (ref = data.txt) != null ? ref.de : void 0 : void 0;
    }
    xuri = 'https://iconclass.org/' + data.n;
    html += '<div style="font-size: 12px; color: #999;"><span class="cui-label-icon"><i class="fa  fa-external-link"></i></span>&nbsp;' + xuri + '</div>';
    html += '<h3><span class="cui-label-icon"><i class="fa  fa-info-circle"></i></span>&nbsp;' + prefLabel + '</h3>';
    keywordsString = '';
    keywords = [];
    if (data != null ? (ref1 = data.kw) != null ? ref1.language : void 0 : void 0) {
      keywords = data != null ? (ref2 = data.kw) != null ? ref2.language : void 0 : void 0;
    } else {
      keywords = data != null ? (ref3 = data.kw) != null ? ref3.de : void 0 : void 0;
    }
    for (key in keywords) {
      val = keywords[key];
      keywordsString = ' - ' + val + '<br />' + keywordsString;
    }
    if (keywordsString) {
      html += '<h4>' + $$('custom.data.type.iconclass.modal.form.popup.preview.keywords') + '</h4>' + keywordsString;
    }
    html = '<style>.iconclassTooltip { padding: 10px; min-width:200px; } .iconclassTooltip h4 { margin-bottom: 0px; }</style><div class="iconclassTooltip">' + html + '</div>';
    return html;
  };

  IconclassUtil.getConceptNameFromObject = function(object, cdata) {
    var activeFrontendLanguage, conceptName, ref, ref1, ref2;
    if (cdata != null ? cdata.frontendLanguage : void 0) {
      if ((cdata != null ? (ref = cdata.frontendLanguage) != null ? ref.length : void 0 : void 0) === 2) {
        activeFrontendLanguage = cdata.frontendLanguage;
      }
    }
    if (Array.isArray(object)) {
      object = object[0];
    }
    conceptName = '';
    if (object.txt[activeFrontendLanguage]) {
      conceptName = object.txt[activeFrontendLanguage];
    } else if (typeof iconclassInfo !== "undefined" && iconclassInfo !== null ? (ref1 = iconclassInfo.txt) != null ? ref1.de : void 0 : void 0) {
      conceptName = object.txt.de;
    } else if (typeof iconclassInfo !== "undefined" && iconclassInfo !== null ? (ref2 = iconclassInfo.txt) != null ? ref2.en : void 0 : void 0) {
      conceptName = object.txt.en;
    } else {
      conceptName = object.txt[Object.keys(object.txt)[0]];
    }
    conceptName = object.n + ' - ' + conceptName;
    return conceptName;
  };

  IconclassUtil.getStandardTextFromObject = function(context, object, cdata, databaseLanguages) {
    var _standard, activeFrontendLanguage, i, l10nObject, l10nObjectKey, l10nObjectValue, language, len, ref, shortenedDatabaseLanguages, shortenedLanguage, standardTextString;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getDatabaseLanguages();
    }
    shortenedDatabaseLanguages = databaseLanguages.map(function(value, key, array) {
      return value.split('-').shift();
    });
    activeFrontendLanguage = null;
    if (context) {
      activeFrontendLanguage = context.getFrontendLanguage();
    }
    if (cdata != null ? cdata.frontendLanguage : void 0) {
      if ((cdata != null ? (ref = cdata.frontendLanguage) != null ? ref.length : void 0 : void 0) === 2) {
        activeFrontendLanguage = cdata.frontendLanguage;
      }
    }
    if (Array.isArray(object)) {
      object = object[0];
    }
    _standard = {};
    standardTextString = '';
    l10nObject = {};
    for (i = 0, len = databaseLanguages.length; i < len; i++) {
      language = databaseLanguages[i];
      l10nObject[language] = '';
    }
    if (object.txt[activeFrontendLanguage]) {
      standardTextString = object.txt[activeFrontendLanguage];
    } else {
      standardTextString = object.txt[Object.keys(object.txt)[0]];
    }
    standardTextString = object.n + ' - ' + standardTextString;
    for (l10nObjectKey in l10nObject) {
      l10nObjectValue = l10nObject[l10nObjectKey];
      shortenedLanguage = l10nObjectKey.split('-')[0];
      if (object.txt[shortenedLanguage]) {
        l10nObject[l10nObjectKey] = object.n + ' - ' + object.txt[shortenedLanguage];
      }
    }
    _standard.l10ntext = l10nObject;
    return _standard;
  };

  IconclassUtil.getFullTextFromObject = 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, propertyType, ref, ref1, shortenedDatabaseLanguages, shortenedLanguage, value;
    if (databaseLanguages == null) {
      databaseLanguages = false;
    }
    if (databaseLanguages === false) {
      databaseLanguages = ez5.loca.getDatabaseLanguages();
    }
    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 = ["kw", "n", "txt"];
    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];
              fullTextString += arrayValue + ' ';
              for (l10nObjectWithShortenedLanguagesKey in l10nObjectWithShortenedLanguages) {
                l10nObjectWithShortenedLanguagesValue = l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey];
                l10nObjectWithShortenedLanguages[l10nObjectWithShortenedLanguagesKey] = l10nObjectWithShortenedLanguagesValue + arrayValue + ' ';
              }
            }
          } else {
            ref1 = object[key];
            for (objectKey in ref1) {
              objectValue = ref1[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.hasOwnProperty(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;
  };

  return IconclassUtil;

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

iconclassUpdate = (function() {
  function iconclassUpdate() {}

  iconclassUpdate.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://jsontojsonp.gbv.de/?url=https%3A%2F%2Ficonclass.org%2F1.json';
    availabilityCheck_xhr = new CUI.XHR({
      url: testURL
    });
    return availabilityCheck_xhr.start().done(function(data, status, statusText) {
      if ((data != null ? data.n : void 0) === '1') {
        return ez5.respondSuccess({
          state: {
            "start_update": new Date().toUTCString(),
            "databaseLanguages": server_config.base.system.languages.database,
            "default_language": server_config.base.system.update_interval_iconclass.default_language
          }
        });
      } else {
        return ez5.respondError("custom.data.type.iconclass.update.error.generic", {
          error: "Test on iconclass-API was not successfull!"
        });
      }
    });
  };

  iconclassUpdate.prototype.__updateData = function(arg) {
    var ICONCLASSUri, chunkWorkPromise, databaseLanguages, defaultLanguage, default_language, iconclassUris, j, len, object, objects, objectsMap, objectsToUpdate, plugin_config, ref, state, that, timeout;
    objects = arg.objects, plugin_config = arg.plugin_config, state = arg.state;
    that = this;
    objectsMap = {};
    iconclassUris = [];
    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;
      }
      ICONCLASSUri = object.data.conceptURI;
      if (CUI.util.isEmpty(ICONCLASSUri)) {
        continue;
      }
      if (!objectsMap[ICONCLASSUri]) {
        objectsMap[ICONCLASSUri] = [];
      }
      objectsMap[ICONCLASSUri].push(object);
      iconclassUris.push(ICONCLASSUri);
    }
    if (iconclassUris.length === 0) {
      return ez5.respondSuccess({
        payload: []
      });
    }
    timeout = ((ref = plugin_config.update) != null ? ref.timeout : void 0) || 0;
    timeout *= 1000;
    iconclassUris = iconclassUris.filter((function(_this) {
      return function(x, i, a) {
        return a.indexOf(x) === i;
      };
    })(this));
    objectsToUpdate = [];
    chunkWorkPromise = CUI.chunkWork.call(this, {
      items: iconclassUris,
      chunk_size: 1,
      call: (function(_this) {
        return function(items) {
          var deferred, extendedInfo_xhr, originalUri, uri, uriEncoded;
          uri = items[0];
          originalUri = items[0];
          uriEncoded = uri.replace('http%3A', 'https%3A');
          uriEncoded = uriEncoded.replace('http:', 'https:');
          uriEncoded = uriEncoded.replace(/ /g, "%20");
          uriEncoded = uriEncoded.replace(/,/g, "%2C");
          uri = 'https://jsontojsonp.gbv.de/?url=' + CUI.encodeURIComponentNicely(uriEncoded) + '.json';
          deferred = new CUI.Deferred();
          extendedInfo_xhr = new CUI.XHR({
            url: uri
          });
          extendedInfo_xhr.start().done(function(data, status, statusText) {
            var ancestor, cdataFromObjectsMap, conceptAncestors, conceptAncestorsString, k, l, len1, len2, objectsMapKey, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, resultsUri, updatedcdata;
            if (data != null ? data.n : void 0) {
              if (data != null ? data.txt : void 0) {
                resultsUri = 'https://iconclass.org/' + data.n;
                ref1 = objectsMap[originalUri];
                for (objectsMapKey = k = 0, len1 = ref1.length; k < len1; objectsMapKey = ++k) {
                  cdataFromObjectsMap = ref1[objectsMapKey];
                  cdataFromObjectsMap = cdataFromObjectsMap.data;
                  updatedcdata = {};
                  updatedcdata.conceptURI = 'https://iconclass.org/' + data.n;
                  updatedcdata.conceptAncestors = [];
                  conceptAncestors = [];
                  if ((data != null ? (ref2 = data.p) != null ? ref2.length : void 0 : void 0) > 0) {
                    ref3 = data.p;
                    for (l = 0, len2 = ref3.length; l < len2; l++) {
                      ancestor = ref3[l];
                      updatedcdata.conceptAncestors.push('https://iconclass.org/' + ancestor);
                    }
                  }
                  updatedcdata.conceptAncestors.push('https://iconclass.org/' + data.n);
                  conceptAncestorsString = updatedcdata.conceptAncestors.join(' ');
                  updatedcdata.conceptAncestors = conceptAncestorsString;
                  if ((cdataFromObjectsMap != null ? (ref4 = cdataFromObjectsMap.frontendLanguage) != null ? ref4.length : void 0 : void 0) === 2) {
                    updatedcdata.frontendLanguage = cdataFromObjectsMap.frontendLanguage;
                    if ((cdataFromObjectsMap != null ? cdataFromObjectsMap.conceptNameChosenByHand : void 0) === false || !cdataFromObjectsMap.hasOwnProperty('conceptNameChosenByHand')) {
                      updatedcdata.conceptNameChosenByHand = false;
                      if (data['txt']) {
                        if (data['txt'][cdataFromObjectsMap.frontendLanguage]) {
                          if ((ref5 = data['txt']) != null ? ref5[cdataFromObjectsMap.frontendLanguage] : void 0) {
                            updatedcdata.conceptName = data['txt'][cdataFromObjectsMap.frontendLanguage];
                          }
                        }
                      }
                    }
                  }
                  if (!(updatedcdata != null ? updatedcdata.conceptName : void 0)) {
                    if (defaultLanguage) {
                      if ((ref6 = data['txt']) != null ? ref6[defaultLanguage] : void 0) {
                        updatedcdata.conceptName = data['txt'][defaultLanguage];
                      }
                    } else {
                      if ((ref7 = data.txt) != null ? ref7.de : void 0) {
                        updatedcdata.conceptName = data.txt.de;
                      } else if ((ref8 = data.txt) != null ? ref8.en : void 0) {
                        updatedcdata.conceptName = data.txt.en;
                      } else {
                        updatedcdata.conceptName = data.txt[Object.keys(data.txt)[0]];
                      }
                    }
                  }
                  updatedcdata.conceptName = data.n + ' - ' + updatedcdata.conceptName;
                  updatedcdata._standard = ez5.IconclassUtil.getStandardTextFromObject(null, data, cdataFromObjectsMap, databaseLanguages);
                  updatedcdata._fulltext = ez5.IconclassUtil.getFullTextFromObject(data, databaseLanguages);
                  if (that.__hasChanges(objectsMap[originalUri][objectsMapKey].data, updatedcdata)) {
                    objectsMap[originalUri][objectsMapKey].data = updatedcdata;
                    objectsToUpdate.push(objectsMap[originalUri][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.iconclass.update.error.generic", {
          error: "Error connecting to Iconclass"
        });
      };
    })(this));
  };

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

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

  return iconclassUpdate;

})();

module.exports = new iconclassUpdate();
