// Generated by CoffeeScript 1.12.7
var CustomDataTypeGazetteer,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  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;

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

  function CustomDataTypeGazetteer() {
    this.getQueryFieldBadge = bind(this.getQueryFieldBadge, this);
    return CustomDataTypeGazetteer.__super__.constructor.apply(this, arguments);
  }

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

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

  CustomDataTypeGazetteer.prototype.getCustomDataOptionsInDatamodelInfo = function(custom_settings) {
    return [];
  };

  CustomDataTypeGazetteer.prototype.supportsStandard = function() {
    return true;
  };

  CustomDataTypeGazetteer.prototype.renderSearchInput = function(data, opts) {
    if (opts == null) {
      opts = {};
    }
    return new SearchToken({
      column: this,
      data: data,
      fields: opts.fields
    }).getInput().DOM;
  };

  CustomDataTypeGazetteer.prototype.getFieldNamesForSearch = function() {
    return this.__getFieldNames();
  };

  CustomDataTypeGazetteer.prototype.getFieldNamesForSuggest = function() {
    return this.__getFieldNames();
  };

  CustomDataTypeGazetteer.prototype.renderEditorInput = function(data) {
    var content, initData, setContent, waitBlock;
    initData = this.__initData(data);
    content = CUI.dom.div();
    waitBlock = new CUI.WaitBlock({
      element: content
    });
    setContent = (function(_this) {
      return function() {
        var displayOutput, ref, searchInput;
        ref = _this.__initForm(initData), searchInput = ref[0], displayOutput = ref[1];
        searchInput.start();
        displayOutput.start();
        CUI.dom.append(content, searchInput);
        CUI.dom.append(content, displayOutput);
        return waitBlock.destroy();
      };
    })(this);
    waitBlock.show();
    this.__fillMissingData(initData).done(setContent);
    return content;
  };

  CustomDataTypeGazetteer.prototype.renderTableOutput = function(data, _, opts) {
    var content, initData;
    initData = this.__initData(data);
    content = this.__renderOutput({
      data: initData,
      onlyText: true
    });
    return content;
  };

  CustomDataTypeGazetteer.prototype.renderDetailOutput = function(data, _, opts) {
    var content, i, initData, len, plugin, plugins, ref, ref1, setContent, waitBlock;
    initData = this.__initData(data);
    content = CUI.dom.div();
    waitBlock = new CUI.WaitBlock({
      element: content
    });
    setContent = (function(_this) {
      return function() {
        var i, len, mapPlugin, outputFieldElement, plugin, plugins;
        outputFieldElement = _this.__renderOutput({
          data: initData
        });
        CUI.dom.replace(content, outputFieldElement);
        waitBlock.destroy();
        if (CUI.Map.isValidPosition(initData.position) && opts.detail) {
          plugins = opts.detail.getPlugins();
          for (i = 0, len = plugins.length; i < len; i++) {
            plugin = plugins[i];
            if (plugin instanceof MapDetailPlugin) {
              mapPlugin = plugin;
              break;
            }
          }
          if (mapPlugin) {
            return mapPlugin.addMarker({
              position: initData.position,
              iconName: initData.iconName,
              iconColor: "#6786ad"
            });
          }
        }
      };
    })(this);
    waitBlock.show();
    this.__fillMissingData(initData).done(setContent);
    plugins = (ref = (ref1 = opts.detail) != null ? ref1.getPlugins() : void 0) != null ? ref : [];
    for (i = 0, len = plugins.length; i < len; i++) {
      plugin = plugins[i];
      if (typeof MapDetailPlugin !== 'undefined' && plugin instanceof MapDetailPlugin) {
        CUI.Events.listen({
          type: "map-detail-click-location",
          node: content,
          call: (function(_this) {
            return function(_, info) {
              var ref2;
              if (((ref2 = info.data) != null ? ref2.position : void 0) === initData.position) {
                return CUI.dom.scrollIntoView(content);
              }
            };
          })(this)
        });
        break;
      }
    }
    return content;
  };

  CustomDataTypeGazetteer.prototype.renderFieldAsGroup = function() {
    return false;
  };

  CustomDataTypeGazetteer.prototype.getTemplateData = function(data) {
    var ref;
    return data != null ? (ref = data._template) != null ? ref[this.name()] : void 0 : void 0;
  };

  CustomDataTypeGazetteer.prototype.getSaveData = function(data, save_data) {
    var fieldData, templateData;
    fieldData = data[this.name()];
    if (CUI.util.isEmpty(fieldData) || CUI.util.isEmpty(fieldData.gazId)) {
      templateData = this.getTemplateData(data);
      if (!CUI.util.isEmpty(templateData)) {
        return save_data[this.name()] = templateData;
      }
      return save_data[this.name()] = null;
    }
    if (fieldData.notFound) {
      throw new InvalidSaveDataException();
    }
    return save_data[this.name()] = ez5.GazetteerUtil.getSaveDataObject(fieldData);
  };

  CustomDataTypeGazetteer.prototype.getQueryFieldBadge = function(data) {
    var value;
    if (data[(this.name()) + ":unset"]) {
      value = $$("text.column.badge.without");
    } else {
      value = data[this.name()];
    }
    return {
      name: this.nameLocalized(),
      value: value
    };
  };

  CustomDataTypeGazetteer.prototype.getSearchFilter = function(data, key) {
    var filter, phrase, ref, str, val;
    if (key == null) {
      key = this.name();
    }
    if (data[key + ":unset"]) {
      filter = {
        type: "in",
        fields: [this.fullName() + ".displayName"],
        "in": [null]
      };
      filter._unnest = true;
      filter._unset_filter = true;
      return filter;
    }
    filter = CustomDataTypeGazetteer.__super__.getSearchFilter.call(this, data, key);
    if (filter) {
      return filter;
    }
    if (CUI.util.isEmpty(data[key])) {
      return;
    }
    val = data[key];
    ref = Search.getPhrase(val), str = ref[0], phrase = ref[1];
    switch (data[key + ":type"]) {
      case "token":
      case "fulltext":
      case void 0:
        filter = {
          type: "match",
          mode: data[key + ":mode"],
          fields: this.getFieldNamesForSearch(),
          string: str,
          phrase: phrase
        };
        break;
      case "field":
        filter = {
          type: "in",
          fields: this.getFieldNamesForSearch(),
          "in": [str]
        };
    }
    return filter;
  };

  CustomDataTypeGazetteer.prototype.__getFieldNames = function() {
    return [this.fullName() + ".gazId", this.fullName() + ".displayName"];
  };

  CustomDataTypeGazetteer.prototype.__initForm = function(formData) {
    var autocompletionPopup, cleanData, loadingContainer, loadingLabel, noResultsContainer, noResultsLabel, onDelete, outputDiv, outputField, resultsContainer, search, searchData, searchField, searchXHR, setData, showOutputField;
    searchData = {
      q: ""
    };
    resultsContainer = "results";
    loadingContainer = "loading";
    noResultsContainer = "no_results";
    loadingLabel = new LocaLabel({
      loca_key: "autocompletion.loading",
      padded: true
    });
    noResultsLabel = new LocaLabel({
      loca_key: "custom.data.type.gazetteer.search.no-results",
      padded: true
    });
    searchField = new CUI.Input({
      name: "q",
      hidden: true,
      placeholder: $$("custom.data.type.gazetteer.search.placeholder"),
      maximize_horizontal: true,
      data: searchData,
      onDataChanged: (function(_this) {
        return function() {
          return CUI.scheduleCallback({
            ms: 200,
            call: search
          });
        };
      })(this)
    });
    autocompletionPopup = new AutocompletionPopup({
      element: searchField,
      onHide: (function(_this) {
        return function() {
          return autocompletionPopup.hide();
        };
      })(this)
    });
    autocompletionPopup.addContainer(resultsContainer);
    autocompletionPopup.addContainer(loadingContainer);
    autocompletionPopup.addContainer(noResultsContainer);
    outputDiv = CUI.dom.div();
    outputField = new CUI.DataFieldProxy({
      name: "displayName",
      hidden: true,
      element: outputDiv
    });
    onDelete = (function(_this) {
      return function() {
        searchField.show();
        outputField.hide();
        cleanData();
        searchField.reload();
        return CUI.Events.trigger({
          node: searchField,
          type: "editor-changed"
        });
      };
    })(this);
    showOutputField = (function(_this) {
      return function() {
        var card;
        card = _this.__renderOutput({
          data: formData,
          editor: true,
          onDelete: onDelete,
          onModify: function() {
            var id;
            id = formData.gazId;
            onDelete();
            searchData.q = id;
            searchField.reload();
            return search();
          }
        });
        CUI.dom.replace(outputDiv, card);
        return outputField.show();
      };
    })(this);
    cleanData = (function(_this) {
      return function() {
        delete formData.displayName;
        delete formData.gazId;
        delete formData.otherNames;
        delete formData.types;
        delete formData.position;
        return delete formData.iconName;
      };
    })(this);
    setData = (function(_this) {
      return function(object) {
        searchData.q = "";
        return ez5.GazetteerUtil.setObjectData(formData, object);
      };
    })(this);
    searchXHR = null;
    search = (function(_this) {
      return function() {
        if (searchXHR != null) {
          searchXHR.abort();
        }
        autocompletionPopup.emptyContainer(resultsContainer);
        autocompletionPopup.emptyContainer(loadingContainer);
        autocompletionPopup.emptyContainer(noResultsContainer);
        if (searchData.q.length === 0) {
          return;
        }
        autocompletionPopup.getContainer(loadingContainer).replace(loadingLabel);
        autocompletionPopup.show();
        searchXHR = new CUI.XHR({
          method: "GET",
          url: ez5.GazetteerUtil.SEARCH_API_URL + CUI.encodeUrlData(searchData)
        });
        return searchXHR.start().done(function(data) {
          var fn, i, len, object, ref, ref1;
          autocompletionPopup.emptyContainer(loadingContainer);
          if (((ref = data.result) != null ? ref.length : void 0) === 0) {
            autocompletionPopup.getContainer(noResultsContainer).replace(noResultsLabel);
            return;
          }
          ref1 = data.result;
          fn = function(object) {
            var item;
            item = autocompletionPopup.appendItem(resultsContainer, _this.__renderAutocompleteCard(object));
            return CUI.Events.listen({
              type: "click",
              node: item,
              call: function(ev) {
                ev.stopPropagation();
                if (object) {
                  setData(object);
                } else {
                  cleanData();
                }
                searchField.hide();
                showOutputField();
                autocompletionPopup.hide();
                CUI.Events.trigger({
                  node: searchField,
                  type: "editor-changed"
                });
              }
            });
          };
          for (i = 0, len = ref1.length; i < len; i++) {
            object = ref1[i];
            fn(object);
          }
          return CUI.Events.trigger({
            type: "content-resize",
            node: autocompletionPopup
          });
        });
      };
    })(this);
    if (CUI.util.isEmpty(formData) || formData.notFound || !formData.gazId) {
      searchField.show();
    } else {
      showOutputField();
    }
    return [searchField, outputField];
  };

  CustomDataTypeGazetteer.prototype.__initData = function(data) {
    var initData;
    if (!data[this.name()]) {
      initData = {};
      data[this.name()] = initData;
    } else {
      initData = data[this.name()];
    }
    return initData;
  };

  CustomDataTypeGazetteer.prototype.__renderOutput = function(opts) {
    var formData;
    formData = opts.data;
    if (formData.notFound) {
      return new CUI.EmptyLabel({
        text: $$("custom.data.type.gazetteer.preview.id-not-found"),
        "class": "ez-label-invalid"
      });
    }
    if (formData.gazId) {
      return this.__renderCard(opts);
    } else {
      return new CUI.EmptyLabel({
        text: $$("custom.data.type.gazetteer.preview.empty-label")
      });
    }
  };

  CustomDataTypeGazetteer.prototype.__renderAutocompleteCard = function(data) {
    var object;
    object = {};
    ez5.GazetteerUtil.setObjectData(object, data);
    return this.__renderCard({
      data: object,
      small: true
    });
  };

  CustomDataTypeGazetteer.prototype.__renderCard = function(_opts) {
    var content, data, editor, i, j, len, len1, link, list, menuButton, menuItems, onDelete, onModify, onlyText, opts, otherName, otherNameLabels, otherNames, plugin, previewImage, ref, ref1, ref2, showLess, showMore, showMoreLessButton, showingMore, small, type, types, verticalList, verticalListContent;
    opts = CUI.Element.readOpts(_opts, "CustomDataTypeGazetteer.__renderCard", {
      data: {
        check: "PlainObject",
        mandatory: true
      },
      editor: {
        check: Boolean,
        "default": false
      },
      small: {
        check: Boolean,
        "default": false
      },
      onlyText: {
        check: Boolean,
        "default": false
      },
      onDelete: {
        check: Function
      },
      onModify: {
        check: Function
      }
    });
    data = opts.data, editor = opts.editor, small = opts.small, onDelete = opts.onDelete, onModify = opts.onModify, onlyText = opts.onlyText;
    content = [
      new CUI.Label({
        text: data.displayName,
        appearance: "title",
        multiline: true
      })
    ];
    if (onlyText) {
      return content[0];
    }
    link = ez5.GazetteerUtil.PLACE_URL + data.gazId;
    menuItems = [
      new LocaButtonHref({
        loca_key: "custom.data.type.gazetteer.link.button",
        href: link,
        target: "_blank"
      })
    ];
    if (!small) {
      if (CUI.Map.isValidPosition(data.position)) {
        menuItems.push(new LocaButton({
          loca_key: "custom.data.type.gazetteer.preview.button",
          onClick: (function(_this) {
            return function() {
              var previewPopover;
              previewPopover = new CUI.Popover({
                element: menuButton,
                placement: "sw",
                pane: _this.__buildPreviewMap(data.position, data.iconName),
                onHide: function() {
                  return previewPopover.destroy();
                }
              });
              return previewPopover.show();
            };
          })(this)
        }));
      }
      if (editor) {
        menuItems.push(new LocaButton({
          loca_key: "custom.data.type.gazetteer.delete.button",
          onClick: (function(_this) {
            return function() {
              return typeof onDelete === "function" ? onDelete() : void 0;
            };
          })(this)
        }));
        menuItems.push(new LocaButton({
          loca_key: "custom.data.type.gazetteer.modify.button",
          onClick: (function(_this) {
            return function() {
              return typeof onModify === "function" ? onModify() : void 0;
            };
          })(this)
        }));
      }
      menuButton = new LocaButton({
        loca_key: "custom.data.type.gazetteer.menu.button",
        icon: "ellipsis_v",
        icon_right: false,
        appearance: "flat",
        menu: {
          items: menuItems
        }
      });
    }
    if (data.types) {
      types = [];
      ref = data.types;
      for (i = 0, len = ref.length; i < len; i++) {
        type = ref[i];
        types.push($$("custom.data.type.gazetteer.types." + type + ".text"));
      }
      content.push(new CUI.Label({
        text: types.join(", "),
        appearance: "secondary"
      }));
    }
    if (!CUI.util.isEmpty(data.otherNames) && ((ref1 = ez5.session.getBaseConfig("plugin", "custom-data-type-gazetteer").gazetteer_plugin_settings) != null ? ref1.show_alternative_names : void 0)) {
      otherNameLabels = [];
      showingMore = false;
      showMoreLessButton = new CUI.Button({
        text: "",
        appearance: "link",
        size: "mini",
        onClick: (function(_this) {
          return function() {
            if (showingMore) {
              showLess();
            } else {
              showMore();
            }
            return showingMore = !showingMore;
          };
        })(this)
      });
      CUI.dom.hideElement(showMoreLessButton);
      showLess = function() {
        var j, k, label, len1, level;
        for (j = 0, len1 = otherNameLabels.length; j < len1; j++) {
          label = otherNameLabels[j];
          CUI.dom.hideElement(label);
        }
        for (level = k = 0; k <= 3; level = k += 1) {
          if (!otherNameLabels[level]) {
            continue;
          }
          CUI.dom.showElement(otherNameLabels[level]);
        }
        if (otherNameLabels.length > 4) {
          showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-more-button"));
          CUI.dom.showElement(showMoreLessButton);
        }
      };
      showMore = function() {
        var j, label, len1;
        for (j = 0, len1 = otherNameLabels.length; j < len1; j++) {
          label = otherNameLabels[j];
          CUI.dom.showElement(label);
        }
        showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-less-button"));
      };
      otherNames = data.otherNames.map(function(otherName) {
        return otherName.title;
      });
      for (j = 0, len1 = otherNames.length; j < len1; j++) {
        otherName = otherNames[j];
        otherNameLabels.push(new CUI.Label({
          text: otherName,
          appearance: "secondary"
        }));
      }
      showLess();
      verticalListContent = small ? otherNameLabels : otherNameLabels.concat([showMoreLessButton]);
      verticalList = new CUI.VerticalList({
        content: verticalListContent
      });
      content.push(verticalList);
    }
    if (!CUI.util.isEmpty(data.position) && ((ref2 = ez5.session.getBaseConfig("plugin", "custom-data-type-gazetteer").gazetteer_plugin_settings) != null ? ref2.show_lat_lng : void 0)) {
      content.push(new CUI.Label({
        text: $$("custom.data.type.gazetteer.types.latitude_longitude.text", data.position),
        appearance: "secondary"
      }));
    }
    list = new CUI.VerticalList({
      content: content
    });
    if (small) {
      return list;
    } else {
      plugin = ez5.pluginManager.getPlugin("custom-data-type-gazetteer");
      previewImage = new Image(36, 36);
      previewImage.src = plugin.getBaseURL() + plugin.getWebfrontend().logo;
      return new CUI.HorizontalLayout({
        "class": "ez5-field-object ez5-custom-data-type-gazetteer-card",
        left: {
          content: previewImage
        },
        center: {
          content: list
        },
        right: {
          content: menuButton
        }
      });
    }
  };

  CustomDataTypeGazetteer.prototype.__buildPreviewMap = function(position, iconName) {
    return new CUI.MapInput.defaults.mapClass({
      selectedMarkerPosition: position,
      selectedMarkerOptions: {
        iconName: iconName,
        iconColor: "#6786ad"
      },
      centerPosition: position,
      clickable: false,
      zoom: 10
    });
  };

  CustomDataTypeGazetteer.prototype.__fillMissingData = function(data) {
    var deferred;
    if (data.gazId && (!data.displayName || !data.types)) {
      deferred = new CUI.Deferred();
      ez5.GazetteerUtil.searchById(data.gazId).done((function(_this) {
        return function(dataFound) {
          return ez5.GazetteerUtil.setObjectData(data, dataFound);
        };
      })(this)).fail((function(_this) {
        return function() {
          return data.notFound = true;
        };
      })(this)).always(deferred.resolve);
      return deferred.promise();
    } else {
      return CUI.resolvedPromise();
    }
  };

  CustomDataTypeGazetteer.prototype.isPluginSupported = function(plugin) {
    if (plugin instanceof MapDetailPlugin) {
      return true;
    }
    return false;
  };

  return CustomDataTypeGazetteer;

})(CustomDataType);

CustomDataType.register(CustomDataTypeGazetteer);
