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

  GazetteerUtil.SEARCH_API_URL = "https://gazetteer.dainst.org/search.json?limit=20&";

  GazetteerUtil.SEARCH_QUERY_API_URL = "https://gazetteer.dainst.org/search.json?q=";

  GazetteerUtil.ID_API_URL = "https://gazetteer.dainst.org/doc/";

  GazetteerUtil.PLACE_URL = "https://gazetteer.dainst.org/place/";

  GazetteerUtil.JSON_EXTENSION = ".json";

  GazetteerUtil.searchById = function(id) {
    var xhr;
    xhr = new CUI.XHR({
      method: "GET",
      url: ez5.GazetteerUtil.ID_API_URL + id + ez5.GazetteerUtil.JSON_EXTENSION
    });
    return xhr.start();
  };

  GazetteerUtil.searchByQuery = function(query, _options) {
    var options, xhr;
    if (_options == null) {
      _options = {};
    }
    options = {
      method: "GET",
      url: ez5.GazetteerUtil.SEARCH_QUERY_API_URL + query
    };
    CUI.util.mergeMap(options, _options);
    xhr = new CUI.XHR(options);
    return xhr.start();
  };

  GazetteerUtil.setObjectData = function(object, data) {
    var position, ref, ref1, ref2, ref3;
    if (CUI.util.isEmpty(data)) {
      return object;
    }
    delete object.notFound;
    object.displayName = (ref = data.prefName) != null ? ref.title : void 0;
    object.gazId = data.gazId;
    object.otherNames = data.names;
    object.types = data.types || [];
    if ((ref1 = data.prefLocation) != null ? ref1.coordinates : void 0) {
      position = {
        lng: (ref2 = data.prefLocation) != null ? ref2.coordinates[0] : void 0,
        lat: (ref3 = data.prefLocation) != null ? ref3.coordinates[1] : void 0
      };
      if (CUI.Map.isValidPosition(position)) {
        object.position = position;
        object.iconName = data.prefLocation ? "fa-map" : "fa-map-marker";
      }
    }
    return object;
  };

  GazetteerUtil.getSaveDataObject = function(data) {
    var fulltext, object, ref;
    fulltext = data.displayName;
    if (((ref = data.otherNames) != null ? ref.length : void 0) > 0) {
      fulltext = data.otherNames.map(function(otherName) {
        return otherName.title;
      }).concat(fulltext).join(' ');
    }
    object = {
      displayName: data.displayName,
      gazId: data.gazId,
      position: data.position,
      iconName: data.iconName,
      otherNames: data.otherNames,
      types: data.types,
      _fulltext: {
        text: fulltext,
        string: data.gazId
      },
      _standard: {
        text: data.displayName
      }
    };
    return object;
  };

  return GazetteerUtil;

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

GazetteerUpdate = (function() {
  function GazetteerUpdate() {}

  GazetteerUpdate.prototype.__start_update = function(arg) {
    var plugin_config, server_config;
    server_config = arg.server_config, plugin_config = arg.plugin_config;
    return ez5.respondSuccess({
      state: {
        "start_update": new Date().toUTCString()
      }
    });
  };

  GazetteerUpdate.prototype.__updateData = function(arg) {
    var gazId, i, len, object, objects, objectsMap, plugin_config, ref, searchIds, searchQuery, timeout;
    objects = arg.objects, plugin_config = arg.plugin_config;
    objectsMap = {};
    searchIds = [];
    for (i = 0, len = objects.length; i < len; i++) {
      object = objects[i];
      if (!(object.identifier && object.data)) {
        continue;
      }
      gazId = object.data.gazId;
      if (CUI.util.isEmpty(gazId)) {
        continue;
      }
      if (!objectsMap[gazId]) {
        objectsMap[gazId] = [];
      }
      objectsMap[gazId].push(object);
      searchIds.push("_id:" + gazId);
    }
    if (searchIds.length === 0) {
      return ez5.respondSuccess({
        payload: []
      });
    }
    timeout = ((ref = plugin_config.update) != null ? ref.timeout : void 0) || 0;
    timeout *= 1000;
    searchQuery = searchIds.join(" OR ");
    searchQuery = CUI.encodeURIComponentNicely(searchQuery);
    return ez5.GazetteerUtil.searchByQuery(searchQuery, {
      timeout: timeout
    }).done((function(_this) {
      return function(data) {
        var _object, gazObject, gazObjects, j, k, len1, len2, objectsToUpdate, ref1;
        objectsToUpdate = [];
        gazObjects = data.result;
        for (j = 0, len1 = gazObjects.length; j < len1; j++) {
          gazObject = gazObjects[j];
          if (!objectsMap[gazObject.gazId]) {
            continue;
          }
          gazObject = ez5.GazetteerUtil.setObjectData({}, gazObject);
          ref1 = objectsMap[gazObject.gazId];
          for (k = 0, len2 = ref1.length; k < len2; k++) {
            _object = ref1[k];
            if (!_this.__hasChanges(_object.data, gazObject)) {
              continue;
            }
            _object.data = ez5.GazetteerUtil.getSaveDataObject(gazObject);
            objectsToUpdate.push(_object);
          }
        }
        return ez5.respondSuccess({
          payload: objectsToUpdate
        });
      };
    })(this)).fail((function(_this) {
      return function(e) {
        return ez5.respondError("custom.data.type.gazeteer.update.error.generic", {
          searchQuery: searchQuery,
          error: e + ""
        });
      };
    })(this));
  };

  GazetteerUpdate.prototype.__hasChanges = function(objectOne, objectTwo) {
    var i, key, len, ref;
    ref = ["displayName", "gazId", "otherNames", "types", "position", "iconName", "_fulltext"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (!CUI.util.isEqual(objectOne[key], objectTwo[key])) {
        return true;
      }
    }
    return false;
  };

  GazetteerUpdate.prototype.main = function(data) {
    var i, key, len, ref;
    if (!data) {
      ez5.respondError("custom.data.type.gazeteer.update.error.payload-missing");
      return;
    }
    ref = ["action", "server_config", "plugin_config"];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      if (!data[key]) {
        ez5.respondError("custom.data.type.gazeteer.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.gazeteer.update.error.objects-missing");
        return;
      }
      if (!(data.objects instanceof Array)) {
        ez5.respondError("custom.data.type.gazeteer.update.error.objects-not-array");
        return;
      }
      if (!data.state) {
        ez5.respondError("custom.data.type.gazeteer.update.error.state-missing");
        return;
      }
      if (!data.batch_info) {
        ez5.respondError("custom.data.type.gazeteer.update.error.batch_info-missing");
        return;
      }
      this.__updateData(data);
    } else {
      return ez5.respondError("custom.data.type.gazeteer.update.error.invalid-action", {
        action: data.action
      });
    }
  };

  return GazetteerUpdate;

})();

module.exports = new GazetteerUpdate();
