// Generated by CoffeeScript 1.12.7
var CustomDataTypeIconclass,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

CustomDataTypeIconclass = (function(superClass) {
  extend(CustomDataTypeIconclass, superClass);

  function CustomDataTypeIconclass() {
    return CustomDataTypeIconclass.__super__.constructor.apply(this, arguments);
  }

  CustomDataTypeIconclass.prototype.getCustomDataTypeName = function() {
    return "custom:base.custom-data-type-iconclass.iconclass";
  };

  CustomDataTypeIconclass.prototype.getCustomMaskSettings = function() {
    if (this.ColumnSchema) {
      return this.FieldSchema.custom_settings || {};
    } else {
      return {};
    }
  };

  CustomDataTypeIconclass.prototype.getCustomSchemaSettings = function() {
    if (this.ColumnSchema) {
      return this.ColumnSchema.custom_settings || {};
    } else {
      return {};
    }
  };

  CustomDataTypeIconclass.prototype.name = function(opts) {
    var ref;
    if (opts == null) {
      opts = {};
    }
    if (!this.ColumnSchema) {
      if ((opts != null ? opts.callfrompoolmanager : void 0) && (opts != null ? opts.name : void 0) !== '') {
        return opts.name;
      } else {
        return "noNameSet";
      }
    } else {
      return (ref = this.ColumnSchema) != null ? ref.name : void 0;
    }
  };

  CustomDataTypeIconclass.prototype.getCustomDataTypeNameLocalized = function() {
    return $$("custom.data.type.iconclass.name");
  };

  CustomDataTypeIconclass.prototype.renderSearchInput = function(data) {
    var form, that;
    that = this;
    if (!data[this.name()]) {
      data[this.name()] = {};
    }
    form = this.renderEditorInput(data, '', {});
    CUI.Events.listen({
      type: "data-changed",
      node: form,
      call: (function(_this) {
        return function() {
          return CUI.Events.trigger({
            type: "search-input-change",
            node: form
          });
        };
      })(this)
    });
    return form.DOM;
  };

  CustomDataTypeIconclass.prototype.getSearchFilter = function(data, key) {
    var filter, ref, that;
    if (key == null) {
      key = this.name();
    }
    that = this;
    if (data[key + ":unset"]) {
      filter = {
        type: "in",
        fields: [this.fullName() + ".conceptName"],
        "in": [null]
      };
      filter._unnest = true;
      filter._unset_filter = true;
      return filter;
    }
    filter = {
      type: "complex",
      search: [
        {
          type: "match",
          bool: "must",
          mode: "token",
          phrase: false,
          fields: [this.path() + '.' + this.name() + ".conceptAncestors"]
        }
      ]
    };
    if (!data[this.name()]) {
      filter.search[0].string = null;
    } else if ((ref = data[this.name()]) != null ? ref.conceptURI : void 0) {
      filter.search[0].string = data[this.name()].conceptURI;
    } else {
      filter = null;
    }
    return filter;
  };

  CustomDataTypeIconclass.prototype.getQueryFieldBadge = function(data) {
    var ref, value;
    if (!data[this.name()]) {
      value = $$("field.search.badge.without");
    } else if (!((ref = data[this.name()]) != null ? ref.conceptURI : void 0)) {
      value = $$("field.search.badge.without");
    } else {
      value = data[this.name()].conceptName;
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  CustomDataTypeIconclass.prototype.__updateSuggestionsMenu = function(cdata, cdata_form, input_searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) {
    var delayMillisseconds, itemList, menu_items, that;
    that = this;
    delayMillisseconds = 50;
    menu_items = [
      {
        text: $$('custom.data.type.iconclass.modal.form.loadingSuggestions'),
        icon_left: new CUI.Icon({
          "class": "fa-spinner fa-spin"
        }),
        disabled: true
      }
    ];
    itemList = {
      items: menu_items
    };
    suggest_Menu.setItemList(itemList);
    return setTimeout((function() {
      var activeFrontendLanguage, countSuggestions, searchStringIsNotation, searchUrl;
      input_searchstring = input_searchstring.replace(/^\s+|\s+$/g, "");
      input_searchstring = input_searchstring.replace('*', '');
      input_searchstring = input_searchstring.replace(' ', '');
      searchStringIsNotation = false;
      if (isNaN(input_searchstring[0]) === false) {
        searchStringIsNotation = true;
      }
      suggest_Menu.show();
      countSuggestions = 20;
      if (searchsuggest_xhr.xhr !== void 0) {
        searchsuggest_xhr.xhr.abort();
      }
      activeFrontendLanguage = that.getFrontendLanguage();
      searchUrl = 'https://iconclass.org/api/search?q=' + encodeURIComponent(input_searchstring) + '&lang=' + activeFrontendLanguage + '&size=999&page=1&sort=rank&keys=0';
      if (searchStringIsNotation) {
        searchUrl = 'https://iconclass.org/' + encodeURIComponent(input_searchstring) + '.json';
      }
      searchsuggest_xhr.xhr = new CUI.XHR({
        url: searchUrl
      });
      return searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
        var extendedInfo_xhr, fn, i, key, len, suggestion;
        extendedInfo_xhr = {
          "xhr": void 0
        };
        if (!searchStringIsNotation) {
          if (data.result) {
            data = data.result;
          }
        } else {
          if (data.length !== 0) {
            data = [data];
          }
        }
        menu_items = [];
        if (data) {
          fn = function(key) {
            var item, suggestionsLabel, suggestionsURI;
            if (JSON.stringify(suggestion) !== '{}') {
              if (searchStringIsNotation) {
                if (suggestion.txt[activeFrontendLanguage]) {
                  suggestionsLabel = suggestion.txt[activeFrontendLanguage];
                } else {
                  suggestionsLabel = suggestion.txt.de;
                }
                suggestionsLabel = suggestion.n + ' - ' + suggestionsLabel;
                suggestionsURI = 'https://iconclass.org/' + suggestion.n;
                item = {
                  text: suggestionsLabel,
                  value: suggestion,
                  tooltip: {
                    markdown: true,
                    placement: "ne",
                    content: function(tooltip) {
                      that.__getAdditionalTooltipInfo(suggestionsURI, tooltip, extendedInfo_xhr);
                      return new CUI.Label({
                        icon: "spinner",
                        text: $$('custom.data.type.iconclass.modal.form.popup.loadingstring')
                      });
                    }
                  }
                };
                menu_items.push(item);
              }
              if (!searchStringIsNotation) {
                suggestionsURI = 'https://iconclass.org/' + suggestion;
                item = {
                  text: suggestion,
                  value: suggestion,
                  tooltip: {
                    markdown: true,
                    placement: "ne",
                    content: function(tooltip) {
                      that.__getAdditionalTooltipInfo(suggestionsURI, tooltip, extendedInfo_xhr);
                      return new CUI.Label({
                        icon: "spinner",
                        text: $$('custom.data.type.iconclass.modal.form.popup.loadingstring')
                      });
                    }
                  }
                };
                return menu_items.push(item);
              }
            }
          };
          for (key = i = 0, len = data.length; i < len; key = ++i) {
            suggestion = data[key];
            fn(key);
          }
        }
        itemList = {
          onClick: function(ev2, btn) {
            var chosenTempUri, fullInfoUrl, iconclassInfo;
            iconclassInfo = btn.getOpt("value");
            if (!(iconclassInfo != null ? iconclassInfo.n : void 0)) {
              cdata.conceptURI = 'https://iconclass.org/' + iconclassInfo;
              cdata.frontendLanguage = activeFrontendLanguage;
              fullInfoUrl = cdata.conceptURI + '.json';
              searchsuggest_xhr.xhr = new CUI.XHR({
                url: fullInfoUrl
              });
              searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
                var ancestor, j, len1, ref, ref1;
                extendedInfo_xhr = {
                  "xhr": void 0
                };
                iconclassInfo = data;
                cdata.conceptName = ez5.IconclassUtil.getConceptNameFromObject(iconclassInfo, cdata);
                cdata.conceptAncestors = [];
                if ((iconclassInfo != null ? (ref = iconclassInfo.p) != null ? ref.length : void 0 : void 0) > 0) {
                  ref1 = iconclassInfo.p;
                  for (j = 0, len1 = ref1.length; j < len1; j++) {
                    ancestor = ref1[j];
                    cdata.conceptAncestors.push('https://iconclass.org/' + ancestor);
                  }
                }
                cdata.conceptAncestors.push('https://iconclass.org/' + iconclassInfo.n);
                cdata.conceptAncestors = cdata.conceptAncestors.join(' ');
                cdata._fulltext = ez5.IconclassUtil.getFullTextFromObject(iconclassInfo, false);
                cdata._standard = ez5.IconclassUtil.getStandardTextFromObject(that, iconclassInfo, cdata, false);
                that.__updateResult(cdata, layout, opts);
                return this;
              });
            }
            if (iconclassInfo != null ? iconclassInfo.n : void 0) {
              if (iconclassInfo.n.includes('(...)')) {
                chosenTempUri = 'https://iconclass.org/' + iconclassInfo.n;
                return CUI.prompt({
                  text: $$('custom.data.type.iconclass.modal.form.popup.brackets.select') + " " + chosenTempUri + "\n\n" + $$('custom.data.type.iconclass.modal.form.popup.brackets.choose')
                }, "1").done((function(_this) {
                  return function(input) {
                    var ancestor, iconclassLabelKey, iconclassLabelValue, inputLowerCase, inputUpperCase, j, len1, newLabel, ref, ref1, ref2;
                    inputUpperCase = input.toUpperCase();
                    inputLowerCase = input.toLowerCase();
                    iconclassInfo.n = iconclassInfo.n.replace('(...)', "(" + inputUpperCase + ")");
                    ref = iconclassInfo.txt;
                    for (iconclassLabelKey in ref) {
                      iconclassLabelValue = ref[iconclassLabelKey];
                      newLabel = iconclassLabelValue;
                      newLabel = newLabel.replace(" (mit NAMEN)", ': ' + inputLowerCase);
                      newLabel = newLabel.replace(" (with NAME)", ': ' + inputLowerCase);
                      newLabel = newLabel.replace(" (avec NOM)", ': ' + inputLowerCase);
                      newLabel = newLabel.replace(" (col NOME)", ': ' + inputLowerCase);
                      newLabel = newLabel.replace(" (NIMEN kanssa)", ': ' + inputLowerCase);
                      iconclassInfo.txt[iconclassLabelKey] = newLabel;
                    }
                    cdata.conceptURI = 'https://iconclass.org/' + iconclassInfo.n;
                    cdata.frontendLanguage = activeFrontendLanguage;
                    cdata.conceptName = ez5.IconclassUtil.getConceptNameFromObject(iconclassInfo, cdata);
                    cdata.conceptAncestors = [];
                    if ((iconclassInfo != null ? (ref1 = iconclassInfo.p) != null ? ref1.length : void 0 : void 0) > 0) {
                      ref2 = iconclassInfo.p;
                      for (j = 0, len1 = ref2.length; j < len1; j++) {
                        ancestor = ref2[j];
                        cdata.conceptAncestors.push('https://iconclass.org/' + ancestor);
                      }
                    }
                    cdata.conceptAncestors.push('https://iconclass.org/' + iconclassInfo.n);
                    cdata.conceptAncestors = cdata.conceptAncestors.join(' ');
                    cdata._fulltext = ez5.IconclassUtil.getFullTextFromObject(iconclassInfo, false);
                    cdata._standard = ez5.IconclassUtil.getStandardTextFromObject(that, iconclassInfo, cdata, false);
                    that.__updateResult(cdata, layout, opts);
                    return _this;
                  };
                })(this)).fail((function(_this) {
                  return function() {
                    cdata = {};
                    that.__updateResult(cdata, layout, opts);
                    return _this;
                  };
                })(this));
              } else {
                if (iconclassInfo != null ? iconclassInfo.n : void 0) {
                  cdata.conceptURI = 'https://iconclass.org/' + iconclassInfo.n;
                }
                cdata.frontendLanguage = activeFrontendLanguage;
                fullInfoUrl = cdata.conceptURI + '.json';
                searchsuggest_xhr.xhr = new CUI.XHR({
                  url: fullInfoUrl
                });
                return searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
                  var ancestor, j, len1, ref, ref1;
                  extendedInfo_xhr = {
                    "xhr": void 0
                  };
                  iconclassInfo = data;
                  cdata.conceptName = ez5.IconclassUtil.getConceptNameFromObject(iconclassInfo, cdata);
                  cdata.conceptAncestors = [];
                  if ((iconclassInfo != null ? (ref = iconclassInfo.p) != null ? ref.length : void 0 : void 0) > 0) {
                    ref1 = iconclassInfo.p;
                    for (j = 0, len1 = ref1.length; j < len1; j++) {
                      ancestor = ref1[j];
                      cdata.conceptAncestors.push('https://iconclass.org/' + ancestor);
                    }
                  }
                  cdata.conceptAncestors.push('https://iconclass.org/' + iconclassInfo.n);
                  cdata.conceptAncestors = cdata.conceptAncestors.join(' ');
                  cdata._fulltext = ez5.IconclassUtil.getFullTextFromObject(iconclassInfo, false);
                  cdata._standard = ez5.IconclassUtil.getStandardTextFromObject(that, iconclassInfo, cdata, false);
                  that.__updateResult(cdata, layout, opts);
                  return this;
                });
              }
            }
          },
          items: menu_items
        };
        if (itemList.items.length === 0) {
          itemList = {
            items: [
              {
                text: $$('custom.data.type.iconclass.modal.form.popup.suggest.nohit'),
                value: void 0
              }
            ]
          };
        }
        suggest_Menu.setItemList(itemList);
        return suggest_Menu.show();
      });
    }), delayMillisseconds);
  };

  CustomDataTypeIconclass.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var cdata;
    if (!data[this.name()]) {
      cdata = {
        conceptName: '',
        conceptURI: ''
      };
      data[this.name()] = cdata;
    } else {
      cdata = data[this.name()];
    }
    return this.__renderEditorInputPopover(data, cdata, opts);
  };

  CustomDataTypeIconclass.prototype.getFrontendLanguage = function() {
    var desiredLanguage;
    desiredLanguage = ez5.loca.getLanguage();
    desiredLanguage = desiredLanguage.split('-');
    desiredLanguage = desiredLanguage[0];
    return desiredLanguage;
  };

  CustomDataTypeIconclass.prototype.__getAdditionalTooltipInfo = function(iconclassURI, tooltip, extendedInfo_xhr, context) {
    var that, url;
    if (context == null) {
      context = null;
    }
    that = this;
    if (iconclassURI.indexOf('%') !== -1) {
      iconclassURI = decodeURIComponent(iconclassURI);
    }
    if (context) {
      that = context;
    }
    if (extendedInfo_xhr.xhr !== void 0) {
      extendedInfo_xhr.xhr.abort();
    }
    url = iconclassURI + '.json';
    extendedInfo_xhr.xhr = new CUI.XHR({
      url: url
    });
    extendedInfo_xhr.xhr.start().done(function(data, status, statusText) {
      var htmlContent;
      htmlContent = ez5.IconclassUtil.getPreview(data, that.getFrontendLanguage());
      if (htmlContent) {
        tooltip.DOM.innerHTML = htmlContent;
      } else {
        tooltip.DOM.innerHTML = '<div class="iconclassTooltip" style="padding: 10px">' + $$('custom.data.type.iconclass.modal.form.popup.no_information_found') + '</div>';
      }
      return tooltip.autoSize();
    });
  };

  CustomDataTypeIconclass.prototype.buildAndSetTreeviewLayout = function(popover, layout, cdata, cdata_form, that, topMethod, returnDfr, opts) {
    var activeFrontendLanguage, treeview, treeviewDfr, treeviewPane;
    if (topMethod == null) {
      topMethod = 0;
    }
    if (returnDfr == null) {
      returnDfr = false;
    }
    that = this;
    treeview = new Iconclass_ListViewTree(popover, layout, cdata, cdata_form, that, opts);
    activeFrontendLanguage = that.getFrontendLanguage();
    if (returnDfr === false) {
      treeview.getTopTreeView(activeFrontendLanguage);
    } else {
      treeviewDfr = treeview.getTopTreeView(activeFrontendLanguage);
    }
    treeviewPane = new CUI.Pane({
      "class": "cui-pane iconclass_treeviewPane",
      top: {
        content: [
          new CUI.PaneHeader({
            left: {
              content: new CUI.Label({
                text: $$('custom.data.type.iconclass.modal.form.popup.choose')
              })
            }
          })
        ]
      },
      center: {
        content: [treeview.treeview, cdata_form]
      }
    });
    this.popover.setContent(treeviewPane);
    if (returnDfr === false) {
      return treeview;
    } else {
      return treeviewDfr;
    }
  };

  CustomDataTypeIconclass.prototype.showEditPopover = function(btn, data, cdata, layout, opts) {
    var that;
    that = this;
    this.popover = new CUI.Popover({
      element: btn,
      placement: "wn",
      "class": "commonPlugin_Popover"
    });
    this.buildAndSetTreeviewLayout(this.popover, layout, cdata, null, that, 1, false, opts);
    return this.popover.show();
  };

  CustomDataTypeIconclass.prototype.__getEditorFields = function(cdata) {
    var fields, option, that;
    that = this;
    fields = [];
    option = {
      type: CUI.Input,
      "class": "commonPlugin_Input",
      undo_and_changed_support: false,
      form: {
        label: $$("custom.data.type.iconclass.modal.form.text.searchbar")
      },
      placeholder: $$("custom.data.type.iconclass.modal.form.text.searchbar.placeholder"),
      name: "searchbarInput"
    };
    fields.push(option);
    return fields;
  };

  CustomDataTypeIconclass.prototype.getDataStatus = function(cdata) {
    var nameCheck, uriCheck;
    if (cdata) {
      if (cdata.conceptURI && cdata.conceptName) {
        uriCheck = false;
        if (cdata.conceptURI.trim() !== '') {
          uriCheck = true;
        }
        nameCheck = cdata.conceptName ? cdata.conceptName.trim() : void 0;
        if (uriCheck && nameCheck) {
          return "ok";
        }
        if (cdata.conceptURI.trim() === '' || cdata.conceptName.trim() === '') {
          return "empty";
        }
        return "invalid";
      }
    }
    return "empty";
  };

  CustomDataTypeIconclass.prototype.__renderButtonByData = function(cdata) {
    var extendedInfo_xhr, frontendLanguage, outputLabel, ref, ref1, that;
    that = this;
    switch (this.getDataStatus(cdata)) {
      case "empty":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.iconclass.edit.no_entry")
        }).DOM;
      case "invalid":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.iconclass.edit.no_valid_entry")
        }).DOM;
    }
    extendedInfo_xhr = {
      "xhr": void 0
    };
    frontendLanguage = ez5.loca.getLanguage();
    outputLabel = cdata.conceptName;
    if ((cdata != null ? (ref = cdata._standard) != null ? (ref1 = ref.l10ntext) != null ? ref1[frontendLanguage] : void 0 : void 0 : void 0) && (cdata != null ? cdata.conceptNameChosenByHand : void 0) !== true) {
      outputLabel = cdata._standard.l10ntext[frontendLanguage];
    }
    cdata.conceptURI;
    return new CUI.HorizontalLayout({
      maximize: true,
      left: {
        content: new CUI.Label({
          centered: false,
          text: outputLabel
        })
      },
      center: {
        content: new CUI.ButtonHref({
          name: "outputButtonHref",
          "class": "pluginResultButton",
          appearance: "link",
          size: "normal",
          href: cdata.conceptURI,
          target: "_blank",
          "class": "cdt_iconclass_smallMarginTop",
          tooltip: {
            markdown: true,
            placement: 'nw',
            content: function(tooltip) {
              that.__getAdditionalTooltipInfo(cdata.conceptURI, tooltip, extendedInfo_xhr);
              return new CUI.Label({
                icon: "spinner",
                text: $$('custom.data.type.iconclass.modal.form.popup.loadingstring')
              });
            }
          }
        })
      },
      right: null
    }).DOM;
  };

  CustomDataTypeIconclass.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    if (Object.keys(custom_settings).length === 0) {
      return ['Ohne Optionen'];
    }
  };

  return CustomDataTypeIconclass;

})(CustomDataTypeWithCommons);

CustomDataType.register(CustomDataTypeIconclass);
