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

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

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

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

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

  CustomDataTypeTNADiscovery.prototype.renderEditorInput = function(data, top_level_data, opts) {
    var cdata;
    if (!data[this.name()]) {
      cdata = {
        conceptName: '',
        conceptURI: '',
        discoveryID: '',
        discoveryURL: '',
        referenceNumber: '',
        locationHeld: '',
        title: '',
        description: ''
      };
      data[this.name()] = cdata;
    } else {
      cdata = data[this.name()];
    }
    return this.__renderEditorInputPopover(data, cdata);
  };

  CustomDataTypeTNADiscovery.prototype.__getAdditionalTooltipInfo = function(uri, tooltip, extendedInfo_xhr) {
    var that;
    that = this;
    uri = decodeURIComponent(uri);
    uri = uri.replace('http://discovery.nationalarchives.gov.uk/details/r/', '');
    if (extendedInfo_xhr.xhr !== void 0) {
      extendedInfo_xhr.xhr.abort();
    }
    extendedInfo_xhr.xhr = new CUI.XHR({
      url: location.protocol + '//jsontojsonp.gbv.de/?url=http%3A%2F%2Fdiscovery.nationalarchives.gov.uk%2FAPI%2Frecords%2Fv1%2Fdetails%2F' + uri
    });
    extendedInfo_xhr.xhr.start().done(function(data, status, statusText) {
      var htmlContent, key, key2, value, value2;
      htmlContent = '';
      for (key in data) {
        if (!hasProp.call(data, key)) continue;
        value = data[key];
        if (value !== null && value !== 'null' && value !== 0 && value !== '0' && value !== '') {
          if (typeof value === 'string') {
            htmlContent = htmlContent + '<b>' + key + ': </b>' + value + '<br /><br />';
          }
          if (typeof value === 'object') {
            if (value.length === void 0) {
              htmlContent = htmlContent + '<b>' + key + ': </b><br />';
              for (key2 in value) {
                if (!hasProp.call(value, key2)) continue;
                value2 = value[key2];
                if (typeof value2 === 'string') {
                  value2 = value2.replace(/<\/?[^>]+(>|$)/g, "");
                  htmlContent = htmlContent + '<u>' + key2 + ': </u>' + value2 + '<br />';
                }
              }
              htmlContent = htmlContent + '<br />';
            }
          }
        }
      }
      htmlContent = '<div style="padding: 8px;">' + htmlContent + '</div>';
      tooltip.DOM.innerHTML = htmlContent;
      return tooltip.autoSize();
    });
  };

  CustomDataTypeTNADiscovery.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 tnadiscovery_countSuggestions, tnadiscovery_searchstring, url;
      tnadiscovery_searchstring = searchstring;
      tnadiscovery_countSuggestions = 20;
      if (cdata_form) {
        tnadiscovery_searchstring = cdata_form.getFieldsByName("searchbarInput")[0].getValue();
        tnadiscovery_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue();
      }
      tnadiscovery_searchstring = '"' + encodeURIComponent(tnadiscovery_searchstring) + '"';
      tnadiscovery_searchstring = encodeURIComponent(tnadiscovery_searchstring);
      if (tnadiscovery_searchstring.length < 2) {
        return;
      }
      if (searchsuggest_xhr.xhr !== void 0) {
        searchsuggest_xhr.xhr.abort();
      }
      url = location.protocol + '//jsontojsonp.gbv.de/?url=http%3A%2F%2Fdiscovery.nationalarchives.gov.uk%2FAPI%2Fsearch%2Fv1%2Frecords%3Fsps.searchQuery%3D' + tnadiscovery_searchstring + '%26sps.sortByOption%3DRELEVANCE%26sps.resultsPageSize%3D' + tnadiscovery_countSuggestions;
      searchsuggest_xhr.xhr = new CUI.XHR({
        url: url
      });
      return searchsuggest_xhr.xhr.start().done(function(data, status, statusText) {
        var extendedInfo_xhr, fn, i, itemList, jsonStrValue, jsonValue, key, len, listStr, menu_items, ref, suggestion;
        extendedInfo_xhr = {
          "xhr": void 0
        };
        menu_items = [];
        ref = data.records;
        fn = function(key) {
          var item;
          item = {
            text: listStr,
            value: jsonStrValue,
            tooltip: {
              markdown: true,
              placement: "e",
              content: function(tooltip) {
                that.__getAdditionalTooltipInfo(suggestion.id, tooltip, extendedInfo_xhr);
                return new CUI.Label({
                  icon: "spinner",
                  text: $$('custom.data.type.tnadiscovery.modal.form.text.loading')
                });
              }
            }
          };
          return menu_items.push(item);
        };
        for (key = i = 0, len = ref.length; i < len; key = ++i) {
          suggestion = ref[key];
          jsonValue = {};
          jsonValue.discoveryID = suggestion.id;
          jsonValue.discoveryURL = 'http://discovery.nationalarchives.gov.uk/details/r/' + suggestion.id;
          jsonValue.referenceNumber = suggestion.reference;
          jsonValue.locationHeld = suggestion.heldBy[0];
          jsonValue.title = suggestion.title;
          jsonValue.description = suggestion.description;
          jsonStrValue = JSON.stringify(jsonValue);
          listStr = suggestion.reference + ': ' + suggestion.title;
          if (listStr.length > 55) {
            listStr = listStr.substring(0, 55) + ' ...';
          }
          fn(key);
        }
        itemList = {
          onClick: function(ev2, btn) {
            jsonStrValue = btn.getOpt("value");
            jsonValue = JSON.parse(jsonStrValue);
            cdata.discoveryID = jsonValue.discoveryID;
            cdata.discoveryURL = jsonValue.discoveryURL;
            cdata.referenceNumber = jsonValue.referenceNumber;
            cdata.locationHeld = jsonValue.locationHeld;
            cdata.title = jsonValue.title;
            cdata.description = jsonValue.description;
            cdata.conceptName = jsonValue.referenceNumber;
            cdata.conceptURI = jsonValue.discoveryURL;
            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: " --- "
              value: undefined
         */
        suggest_Menu.setItemList(itemList);
        return suggest_Menu.show();
      });
    }), delayMillisseconds);
  };

  CustomDataTypeTNADiscovery.prototype.__getEditorFields = function(cdata) {
    var fields, option, ref, that;
    that = this;
    fields = [];
    if (!((ref = that.getCustomMaskSettings().use_tree_view) != null ? ref.value : void 0)) {
      option = {
        type: CUI.Select,
        "class": "commonPlugin_Select",
        undo_and_changed_support: false,
        form: {
          label: $$('custom.data.type.tnadiscovery.modal.form.text.count')
        },
        options: [
          {
            value: 10,
            text: '10 ' + $$('custom.data.type.tnadiscovery.modal.form.text.countX')
          }, {
            value: 20,
            text: '20 ' + $$('custom.data.type.tnadiscovery.modal.form.text.countX')
          }, {
            value: 50,
            text: '50 ' + $$('custom.data.type.tnadiscovery.modal.form.text.countX')
          }, {
            value: 100,
            text: '100 ' + $$('custom.data.type.tnadiscovery.modal.form.text.countX')
          }
        ],
        name: 'countOfSuggestions'
      };
      fields.push(option);
    }
    option = {
      type: CUI.Input,
      "class": "commonPlugin_Input",
      undo_and_changed_support: false,
      form: {
        label: $$("custom.data.type.tnadiscovery.modal.form.text.searchbar")
      },
      placeholder: $$("custom.data.type.tnadiscovery.modal.form.text.searchbar.placeholder"),
      name: "searchbarInput"
    };
    fields.push(option);
    return fields;
  };

  CustomDataTypeTNADiscovery.prototype.getSaveData = function(data, save_data, opts) {
    var cdata, ref;
    if (opts.demo_data) {
      return {
        conceptName: 'conceptName',
        conceptURI: 'conceptURI',
        discoveryID: 'discoveryID',
        discoveryURL: 'http://discoveryURL.tna.org',
        referenceNumber: '123123123',
        locationHeld: 'locationHeld',
        title: 'title title title title',
        description: 'description description description description description description description description description description description description'
      };
    }
    cdata = data[this.name()] || ((ref = data._template) != null ? ref[this.name()] : void 0);
    switch (this.getDataStatus(cdata)) {
      case "invalid":
        throw InvalidSaveDataException;
        break;
      case "empty":
        return save_data[this.name()] = null;
      case "ok":
        return save_data[this.name()] = {
          conceptName: cdata.referenceNumber.trim(),
          conceptURI: cdata.discoveryURL.trim(),
          discoveryID: cdata.discoveryID.trim(),
          discoveryURL: cdata.discoveryURL.trim(),
          referenceNumber: cdata.referenceNumber.trim(),
          locationHeld: cdata.locationHeld.trim(),
          title: cdata.title.trim(),
          description: cdata.description.trim()
        };
    }
  };

  CustomDataTypeTNADiscovery.prototype.getDataStatus = function(cdata) {
    if (cdata) {
      if (cdata.referenceNumber && cdata.title) {
        if (cdata.referenceNumber !== '' && cdata.title !== '') {
          return "ok";
        } else {
          return "empty";
        }
      } else {
        cdata = {
          conceptName: '',
          conceptURI: '',
          discoveryID: '',
          discoveryURL: '',
          referenceNumber: '',
          locationHeld: '',
          title: '',
          description: ''
        };
        return "empty";
      }
    } else {
      cdata = {
        conceptName: '',
        conceptURI: '',
        discoveryID: '',
        discoveryURL: '',
        referenceNumber: '',
        locationHeld: '',
        title: '',
        description: ''
      };
      return "empty";
    }
  };

  CustomDataTypeTNADiscovery.prototype.__updateResult = function(cdata, layout, opts) {
    var displayURI, info, inputX, options, searchsuggest_xhr, suggest_Menu_directInput, that, uriParts, uuid;
    that = this;
    if (cdata != null ? cdata.conceptURI : void 0) {
      displayURI = cdata.conceptURI;
      displayURI = displayURI.replace('http://', '');
      displayURI = displayURI.replace('https://', '');
      uriParts = displayURI.split('/');
      uuid = uriParts.pop();
      if (uuid.length > 10) {
        uuid = uuid.substring(0, 5) + '…';
        uriParts.push(uuid);
        displayURI = uriParts.join('/');
      }
      info = new CUI.VerticalLayout({
        "class": 'ez5-info_commonPlugin',
        top: {
          content: [
            new CUI.Label({
              text: '[' + cdata.referenceNumber + ']',
              multiline: true,
              manage_overflow: true
            }), new CUI.Label({
              text: cdata.title,
              multiline: true,
              manage_overflow: true
            }), new CUI.Label({
              text: cdata.description,
              multiline: true,
              manage_overflow: true
            }), new CUI.Label({
              text: '[' + cdata.locationHeld + ']',
              multiline: true,
              manage_overflow: true
            })
          ]
        },
        bottom: {
          content: new CUI.Button({
            name: "outputButtonHref",
            appearance: "flat",
            size: "normal",
            text: displayURI,
            tooltip: {
              markdown: true,
              placement: 'nw',
              content: function(tooltip) {
                var encodedURI, extendedInfo_xhr;
                encodedURI = encodeURIComponent(cdata.conceptURI);
                extendedInfo_xhr = {
                  "xhr": void 0
                };
                that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr);
                return new CUI.Label({
                  icon: "spinner",
                  text: $$('custom.data.type.dante.modal.form.popup.loadingstring')
                });
              }
            },
            onClick: (function(_this) {
              return function(evt, button) {
                return window.open(cdata.conceptURI, "_blank");
              };
            })(this)
          })
        }
      });
      layout.replace(info, 'center');
      layout.addClass('ez5-linked-object-edit');
      options = {
        "class": 'ez5-linked-object-container'
      };
      layout.__initPane(options, 'center');
    }
    if (!(cdata != null ? cdata.conceptURI : void 0)) {
      suggest_Menu_directInput;
      inputX = new CUI.Input({
        "class": "pluginDirectSelectEditInput",
        undo_and_changed_support: false,
        name: "directSelectInput",
        content_size: false,
        onKeyup: (function(_this) {
          return function(input) {
            var searchstring;
            searchstring = input.getValueForInput();
            return _this.__updateSuggestionsMenu(cdata, 0, searchstring, input, suggest_Menu_directInput, searchsuggest_xhr, layout, opts);
          };
        })(this)
      });
      inputX.render();
      suggest_Menu_directInput = new CUI.Menu({
        element: inputX,
        use_element_width_as_min_width: true
      });
      searchsuggest_xhr = {
        "xhr": void 0
      };
      layout.replace(inputX, 'center');
      layout.removeClass('ez5-linked-object-edit');
      options = {
        "class": ''
      };
      layout.__initPane(options, 'center');
    }
    return that.__setEditorFieldStatus(cdata, layout);
  };

  CustomDataTypeTNADiscovery.prototype.__renderButtonByData = function(cdata) {
    var list, that;
    that = this;
    switch (this.getDataStatus(cdata)) {
      case "empty":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.tnadiscovery.edit.no_tnadiscovery")
        }).DOM;
      case "invalid":
        return new CUI.EmptyLabel({
          text: $$("custom.data.type.tnadiscovery.edit.no_valid_tnadiscovery")
        }).DOM;
    }
    list = new CUI.VerticalList({
      maximize: false,
      content: [
        new CUI.Label({
          text: " "
        }), new CUI.ButtonHref({
          name: "outputButtonHref",
          href: cdata.discoveryURL,
          target: "_blank",
          icon_left: new CUI.Icon({
            "class": "fa-external-link"
          }),
          text: cdata.discoveryURL
        }), new CUI.Label({
          text: cdata.title,
          multiline: true,
          manage_overflow: true
        }), new CUI.Label({
          text: '[' + cdata.referenceNumber + ']',
          multiline: true,
          manage_overflow: true
        }), new CUI.Label({
          text: cdata.description,
          multiline: true,
          manage_overflow: true
        }), new CUI.Label({
          text: '[' + cdata.locationHeld + ']',
          multiline: true,
          manage_overflow: true
        })
      ]
    });
    return list.DOM;
  };

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

  return CustomDataTypeTNADiscovery;

})(CustomDataTypeWithCommons);

CustomDataType.register(CustomDataTypeTNADiscovery);
