// Generated by CoffeeScript 1.12.7
var CustomDataTypeCERLThesaurus,
  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;

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

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

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

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

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

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

  CustomDataTypeCERLThesaurus.prototype.getSearchFilter = function(data, key) {
    var filter, givenURI, givenURIParts, givencerlthesaurusID, ref, that, uri;
    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: "in",
          bool: "must",
          fields: ["_objecttype"],
          "in": [this.path()]
        }, {
          type: "match",
          mode: "token",
          bool: "must",
          phrase: false,
          fields: [this.path() + '.' + this.name() + ".conceptURI"]
        }
      ]
    };
    if (!data[this.name()]) {
      filter.search[1].string = null;
    } else if ((ref = data[this.name()]) != null ? ref.conceptURI : void 0) {
      givenURI = data[this.name()].conceptURI;
      givenURIParts = givenURI.split('/');
      givencerlthesaurusID = givenURIParts.pop();
      uri = 'https://data.cerl.org/thesaurus/' + givencerlthesaurusID;
      filter.search[1].string = uri;
    } else {
      filter = null;
    }
    return filter;
  };

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

  CustomDataTypeCERLThesaurus.prototype.__getAdditionalTooltipInfo = function(uri, tooltip, extendedInfo_xhr) {
    var cerlthesaurusID, cerlthesaurusURI, requestUrl, that;
    that = this;
    cerlthesaurusURI = uri;
    cerlthesaurusID = decodeURIComponent(uri);
    cerlthesaurusID = cerlthesaurusID.split("/");
    cerlthesaurusID = cerlthesaurusID.pop();
    if (extendedInfo_xhr.xhr !== void 0) {
      extendedInfo_xhr.xhr.abort();
    }
    requestUrl = 'https://ws.gbv.de/suggest/cerl_thesaurus/?searchstring=' + cerlthesaurusID + '&type=placename&count=1';
    extendedInfo_xhr.xhr = new CUI.XHR({
      url: requestUrl
    });
    extendedInfo_xhr.xhr.start().done(function(data, status, statusText) {
      var htmlContent, i, len, ref, variantName, variantNameKey, variants, variantsString;
      if (data.length === 0) {
        return;
      }
      data = data[0];
      htmlContent = '<span style="padding: 10px 10px 0px 10px; font-weight: bold">' + $$('custom.data.type.cerlthesaurus.config.parameter.mask.infopop.info.label') + '</span>';
      htmlContent += '<table style="border-spacing: 10px; border-collapse: separate;">';
      if (data.displayName) {
        htmlContent += '<tr><td>' + $$('custom.data.type.cerlthesaurus.config.parameter.mask.infopop.displayName.label') + ':</td><td>' + data.displayName + '</td></tr>';
      }
      if (data.cerlID) {
        htmlContent += '<tr><td>' + $$('custom.data.type.cerlthesaurus.config.parameter.mask.infopop.cerlID.label') + ':</td><td>' + data.cerlID + '</td></tr>';
      }
      if (data.geoNote) {
        htmlContent += '<tr><td>' + $$('custom.data.type.cerlthesaurus.config.parameter.mask.infopop.geoNote.label') + ':</td><td>' + data.geoNote + '</td></tr>';
      }
      if (data.bioData) {
        htmlContent += '<tr><td>' + $$('custom.data.type.cerlthesaurus.config.parameter.mask.infopop.bioData.label') + ':</td><td>' + data.bioData + '</td></tr>';
      }
      if (data.variantForms) {
        variants = [];
        ref = data.variantForms;
        for (variantNameKey = i = 0, len = ref.length; i < len; variantNameKey = ++i) {
          variantName = ref[variantNameKey];
          variants.push(variantName);
        }
        variantsString = variants.join('<br />');
      }
      if (variants.length > 0) {
        htmlContent += '<tr><td>' + $$('custom.data.type.cerlthesaurus.config.parameter.mask.infopop.variantForms.label') + ':</td><td>' + variantsString + '</td></tr>';
      }
      tooltip.DOM.innerHTML = htmlContent;
      return tooltip.autoSize();
    });
  };

  CustomDataTypeCERLThesaurus.prototype.showEditPopover = function(btn, data, cdata, layout, opts) {
    var cdata_form, searchsuggest_xhr, suggest_Menu, that;
    that = this;
    suggest_Menu;
    searchsuggest_xhr = {
      "xhr": void 0
    };
    cdata.countOfSuggestions = 10;
    cdata_form = new CUI.Form({
      "class": 'cdtFormWithPadding',
      data: cdata,
      fields: that.__getEditorFields(cdata),
      onDataChanged: (function(_this) {
        return function(data, elem) {
          var defaultText, featureclassParameter, ref, ref1, ref2, ref3;
          if (((ref = _this.getCustomMaskSettings().config_featureclasses) != null ? ref.value : void 0) && ((ref1 = _this.getCustomMaskSettings().config_featurecodes) != null ? ref1.value : void 0)) {
            if (elem.opts.name === 'cerlthesaurusSelectFeatureClasses') {
              featureclassParameter = '';
              if ((data != null ? data.cerlthesaurusSelectFeatureClasses : void 0) !== '' && (data != null ? data.cerlthesaurusSelectFeatureClasses : void 0) !== null) {
                featureclassParameter = data.cerlthesaurusSelectFeatureClasses;
              }
              data.cerlthesaurusSelectFeatureCodes = null;
              cdata.cerlthesaurusSelectFeatureCodes = null;
              if ((ref2 = cdata_form.getFieldsByName("cerlthesaurusSelectFeatureCodes")[0]) != null) {
                ref2.setValue(null);
              }
              defaultText = cdata_form.getFieldsByName("cerlthesaurusSelectFeatureCodes")[0].default_opt.text;
              cdata_form.getFieldsByName("cerlthesaurusSelectFeatureCodes")[0].reload();
              if ((ref3 = cdata_form.getFieldsByName("cerlthesaurusSelectFeatureCodes")[0]) != null) {
                ref3.setText('test');
              }
            }
          }
          _this.__updateResult(cdata, layout, opts);
          _this.__setEditorFieldStatus(cdata, layout);
          return _this.__updateSuggestionsMenu(cdata, cdata_form, data.searchbarInput, elem, suggest_Menu, searchsuggest_xhr, layout, opts);
        };
      })(this)
    }).start();
    suggest_Menu = new CUI.Menu({
      element: cdata_form.getFieldsByName("searchbarInput")[0],
      use_element_width_as_min_width: true,
      "class": "customDataTypeCommonsMenu"
    });
    return this.popover = new CUI.Popover({
      element: btn,
      placement: "wn",
      "class": "commonPlugin_Popover",
      pane: {
        header_left: new CUI.Label({
          text: $$('custom.data.type.commons.popover.choose.label')
        }),
        content: cdata_form
      }
    }).show();
  };

  CustomDataTypeCERLThesaurus.prototype.__updateSuggestionsMenu = function(cdata, cdata_form, searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) {
    var delayMillisseconds, that;
    that = this;
    delayMillisseconds = 200;
    return setTimeout((function() {
      var cerlthesaurus_countSuggestions, cerlthesaurus_searchterm, cerlthesaurus_type, expandQuery, extendedInfo_xhr, ref, ref1, ref2, ref3, ref4, ref5, ref6, requestUrl;
      cerlthesaurus_searchterm = searchstring;
      cerlthesaurus_countSuggestions = 10;
      if (((ref = that.getCustomMaskSettings()) != null ? (ref1 = ref.allow_corporatename) != null ? ref1.value : void 0 : void 0) === true) {
        cerlthesaurus_type = 'corporatename';
      } else if (((ref2 = that.getCustomMaskSettings()) != null ? (ref3 = ref2.allow_imprintname) != null ? ref3.value : void 0 : void 0) === true) {
        cerlthesaurus_type = 'imprintname';
      } else if (((ref4 = that.getCustomMaskSettings()) != null ? (ref5 = ref4.allow_placename) != null ? ref5.value : void 0 : void 0) === true) {
        cerlthesaurus_type = 'placename';
      } else {
        cerlthesaurus_type = 'personalname';
      }
      expandQuery = '';
      if (cdata_form) {
        cerlthesaurus_searchterm = cdata_form.getFieldsByName("searchbarInput")[0].getValue();
        cerlthesaurus_type = (ref6 = cdata_form.getFieldsByName("cerlthesaurusSelectType")[0]) != null ? ref6.getValue() : void 0;
        if (cerlthesaurus_type === void 0 || cerlthesaurus_type === null) {
          cerlthesaurus_type = '';
        }
        cerlthesaurus_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue();
      }
      if (cerlthesaurus_searchterm.length === 0) {
        return;
      }
      extendedInfo_xhr = {
        "xhr": void 0
      };
      if (searchsuggest_xhr.xhr !== void 0) {
        searchsuggest_xhr.xhr.abort();
      }
      requestUrl = 'https://ws.gbv.de/suggest/cerl_thesaurus/?searchstring=' + cerlthesaurus_searchterm + '&type=' + cerlthesaurus_type + '&count=' + cerlthesaurus_countSuggestions;
      searchsuggest_xhr.xhr = new CUI.XHR({
        url: requestUrl
      });
      return searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
        var fn, i, itemList, key, len, menu_items, suggestion;
        menu_items = [];
        fn = function(key) {
          var item;
          item = {
            text: suggestion.displayName,
            value: 'https://data.cerl.org/thesaurus/' + suggestion.cerlID,
            tooltip: {
              markdown: true,
              placement: "e",
              content: function(tooltip) {
                that.__getAdditionalTooltipInfo('https://data.cerl.org/thesaurus/' + data[key].cerlID, tooltip, extendedInfo_xhr);
                return new CUI.Label({
                  icon: "spinner",
                  text: "lade Informationen"
                });
              }
            }
          };
          return menu_items.push(item);
        };
        for (key = i = 0, len = data.length; i < len; key = ++i) {
          suggestion = data[key];
          fn(key);
        }
        itemList = {
          keyboardControl: true,
          onClick: function(ev2, btn) {
            var cerlthesaurusID, dataEntry_xhr;
            cdata.conceptURI = btn.getOpt("value");
            cdata.conceptName = btn.getText();
            cdata._fulltext = {};
            cdata._standard = {};
            cdata._fulltext.text = cdata.conceptName;
            cdata._standard.text = cdata.conceptName;
            cerlthesaurusID = cdata.conceptURI;
            cerlthesaurusID = cerlthesaurusID.replace('https://data.cerl.org/thesaurus/', '');
            requestUrl = 'https://ws.gbv.de/suggest/cerl_thesaurus/?searchstring=' + cerlthesaurusID + '&type=placename&count=1';
            dataEntry_xhr = new CUI.XHR({
              url: requestUrl
            });
            return dataEntry_xhr.start().done(function(data, status, statusText) {
              data = data[0];
              cdata.conceptName = ez5.CERLThesaurusUtil.getConceptNameFromObject(data);
              cdata.conceptURI = ez5.CERLThesaurusUtil.getConceptURIFromObject(data);
              cdata._fulltext = ez5.CERLThesaurusUtil.getFullTextFromObject(data, false);
              cdata._standard = ez5.CERLThesaurusUtil.getStandardTextFromObject(that, data, cdata, false);
              that.__updateResult(cdata, layout, opts);
              suggest_Menu.hide();
              if (that.popover) {
                return that.popover.hide();
              }
            });
          },
          items: menu_items
        };
        if (itemList.items.length === 0) {
          itemList = {
            items: [
              {
                text: "kein Treffer",
                value: void 0
              }
            ]
          };
        }
        suggest_Menu.setItemList(itemList);
        return suggest_Menu.show();
      });
    }), delayMillisseconds);
  };

  CustomDataTypeCERLThesaurus.prototype.__getEditorFields = function(cdata) {
    var field, fields, newType, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, that, typesOptions;
    that = this;
    fields = [
      {
        type: CUI.Select,
        "class": "commonPlugin_Select",
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.cerlthesaurus.modal.form.text.count')
        },
        options: [
          {
            value: 10,
            text: '10 ' + $$('custom.data.type.cerlthesaurus.modal.form.text.count_short')
          }, {
            value: 20,
            text: '20 ' + $$('custom.data.type.cerlthesaurus.modal.form.text.count_short')
          }, {
            value: 50,
            text: '50 ' + $$('custom.data.type.cerlthesaurus.modal.form.text.count_short')
          }, {
            value: 100,
            text: '100 ' + $$('custom.data.type.cerlthesaurus.modal.form.text.count_short')
          }
        ],
        name: 'countOfSuggestions'
      }, {
        type: CUI.Input,
        "class": "commonPlugin_Input",
        undo_and_changed_support: false,
        form: {
          label: $$("custom.data.type.cerlthesaurus.modal.form.text.searchbar")
        },
        placeholder: $$("custom.data.type.cerlthesaurus.modal.form.text.searchbar.placeholder"),
        name: "searchbarInput"
      }
    ];
    typesOptions = [];
    if (((ref = that.getCustomMaskSettings()) != null ? (ref1 = ref.allow_corporatename) != null ? ref1.value : void 0 : void 0) === true) {
      newType = {
        value: 'corporatename',
        text: $$('custom.data.type.cerl.thesaurus.config.parameter.mask.allow_corporatename.value.label')
      };
      typesOptions.push(newType);
    }
    if (((ref2 = that.getCustomMaskSettings()) != null ? (ref3 = ref2.allow_imprintname) != null ? ref3.value : void 0 : void 0) === true) {
      newType = {
        value: 'imprintname',
        text: $$('custom.data.type.cerl.thesaurus.config.parameter.mask.allow_imprintname.value.label')
      };
      typesOptions.push(newType);
    }
    if (((ref4 = that.getCustomMaskSettings()) != null ? (ref5 = ref4.allow_personalname) != null ? ref5.value : void 0 : void 0) === true) {
      newType = {
        value: 'personalname',
        text: $$('custom.data.type.cerl.thesaurus.config.parameter.mask.allow_personalname.value.label')
      };
      typesOptions.push(newType);
    }
    if (((ref6 = that.getCustomMaskSettings()) != null ? (ref7 = ref6.allow_placename) != null ? ref7.value : void 0 : void 0) === true) {
      newType = {
        value: 'placename',
        text: $$('custom.data.type.cerl.thesaurus.config.parameter.mask.allow_placename.value.label')
      };
      typesOptions.push(newType);
    }
    if (typesOptions.length === 0) {
      newType = {
        value: 'personalname',
        text: $$('custom.data.type.cerl.thesaurus.config.parameter.mask.allow_personalname.value.label')
      };
      typesOptions.push(newType);
    }
    field = {
      type: CUI.Select,
      undo_and_changed_support: false,
      form: {
        label: $$('custom.data.type.cerlthesaurus.modal.form.text.type')
      },
      options: typesOptions,
      name: 'cerlthesaurusSelectType',
      "class": 'commonPlugin_Select'
    };
    fields.unshift(field);
    return fields;
  };

  CustomDataTypeCERLThesaurus.prototype.__renderButtonByData = function(cdata) {
    var extendedInfo_xhr, that;
    that = this;
    switch (this.getDataStatus(cdata)) {
      case "empty":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.cerlthesaurus.edit.no_cerlthesaurus")
        }).DOM;
      case "invalid":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.cerlthesaurus.edit.no_valid_cerlthesaurus")
        }).DOM;
    }
    cdata.conceptURI = CUI.parseLocation(cdata.conceptURI).url;
    extendedInfo_xhr = {
      "xhr": void 0
    };
    return new CUI.HorizontalLayout({
      maximize: false,
      left: {
        content: new CUI.Label({
          centered: false,
          multiline: true,
          text: cdata.conceptName
        })
      },
      center: {
        content: new CUI.ButtonHref({
          appearance: "link",
          href: cdata.conceptURI,
          target: "_blank",
          tooltip: {
            markdown: true,
            placement: 'n',
            content: function(tooltip) {
              that.__getAdditionalTooltipInfo(cdata.conceptURI, tooltip, extendedInfo_xhr);
              return new CUI.Label({
                icon: "spinner",
                text: "lade Informationen"
              });
            }
          },
          text: ' '
        })
      },
      right: null
    }).DOM;
  };

  CustomDataTypeCERLThesaurus.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    var tags;
    tags = [];
    return tags;
  };

  return CustomDataTypeCERLThesaurus;

})(CustomDataTypeWithCommons);

CustomDataType.register(CustomDataTypeCERLThesaurus);
