'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _index = require('../index.js');

var _index2 = _interopRequireDefault(_index);

var _asserts = require('../asserts.js');

var _asserts2 = _interopRequireDefault(_asserts);

var _feature = require('../feature.js');

var _feature2 = _interopRequireDefault(_feature);

var _coordinate = require('../coordinate.js');

var _coordinate2 = _interopRequireDefault(_coordinate);

var _eventtype = require('../events/eventtype.js');

var _eventtype2 = _interopRequireDefault(_eventtype);

var _extent = require('../extent.js');

var _extent2 = _interopRequireDefault(_extent);

var _point = require('../geom/point.js');

var _point2 = _interopRequireDefault(_point);

var _vector = require('../source/vector.js');

var _vector2 = _interopRequireDefault(_vector);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}

/**
 * @classdesc
 * Layer source to cluster vector data. Works out of the box with point
 * geometries. For other geometry types, or if not all geometries should be
 * considered for clustering, a custom `geometryFunction` can be defined.
 *
 * @constructor
 * @param {olx.source.ClusterOptions} options Constructor options.
 * @extends {ol.source.Vector}
 * @api
 */
// FIXME keep cluster cache by resolution ?
// FIXME distance not respected because of the centroid

var _ol_source_Cluster_ = function (options) {
  _vector2.default.call(this, {
    attributions: options.attributions,
    extent: options.extent,
    logo: options.logo,
    projection: options.projection,
    wrapX: options.wrapX
  });

  /**
   * @type {number|undefined}
   * @protected
   */
  this.resolution = undefined;

  /**
   * @type {number}
   * @protected
   */
  this.distance = options.distance !== undefined ? options.distance : 20;

  /**
   * @type {Array.<ol.Feature>}
   * @protected
   */
  this.features = [];

  /**
   * @param {ol.Feature} feature Feature.
   * @return {ol.geom.Point} Cluster calculation point.
   * @protected
   */
  this.geometryFunction = options.geometryFunction || function (feature) {
    var geometry = /** @type {ol.geom.Point} */feature.getGeometry();
    _asserts2.default.assert(geometry instanceof _point2.default, 10); // The default `geometryFunction` can only handle `ol.geom.Point` geometries
    return geometry;
  };

  /**
   * @type {ol.source.Vector}
   * @protected
   */
  this.source = options.source;

  this.source.on(_eventtype2.default.CHANGE, _ol_source_Cluster_.prototype.refresh, this);
};

_index2.default.inherits(_ol_source_Cluster_, _vector2.default);

/**
 * Get the distance in pixels between clusters.
 * @return {number} Distance.
 * @api
 */
_ol_source_Cluster_.prototype.getDistance = function () {
  return this.distance;
};

/**
 * Get a reference to the wrapped source.
 * @return {ol.source.Vector} Source.
 * @api
 */
_ol_source_Cluster_.prototype.getSource = function () {
  return this.source;
};

/**
 * @inheritDoc
 */
_ol_source_Cluster_.prototype.loadFeatures = function (extent, resolution, projection) {
  this.source.loadFeatures(extent, resolution, projection);
  if (resolution !== this.resolution) {
    this.clear();
    this.resolution = resolution;
    this.cluster();
    this.addFeatures(this.features);
  }
};

/**
 * Set the distance in pixels between clusters.
 * @param {number} distance The distance in pixels.
 * @api
 */
_ol_source_Cluster_.prototype.setDistance = function (distance) {
  this.distance = distance;
  this.refresh();
};

/**
 * handle the source changing
 * @override
 */
_ol_source_Cluster_.prototype.refresh = function () {
  this.clear();
  this.cluster();
  this.addFeatures(this.features);
  _vector2.default.prototype.refresh.call(this);
};

/**
 * @protected
 */
_ol_source_Cluster_.prototype.cluster = function () {
  if (this.resolution === undefined) {
    return;
  }
  this.features.length = 0;
  var extent = _extent2.default.createEmpty();
  var mapDistance = this.distance * this.resolution;
  var features = this.source.getFeatures();

  /**
   * @type {!Object.<string, boolean>}
   */
  var clustered = {};

  for (var i = 0, ii = features.length; i < ii; i++) {
    var feature = features[i];
    if (!(_index2.default.getUid(feature).toString() in clustered)) {
      var geometry = this.geometryFunction(feature);
      if (geometry) {
        var coordinates = geometry.getCoordinates();
        _extent2.default.createOrUpdateFromCoordinate(coordinates, extent);
        _extent2.default.buffer(extent, mapDistance, extent);

        var neighbors = this.source.getFeaturesInExtent(extent);
        neighbors = neighbors.filter(function (neighbor) {
          var uid = _index2.default.getUid(neighbor).toString();
          if (!(uid in clustered)) {
            clustered[uid] = true;
            return true;
          } else {
            return false;
          }
        });
        this.features.push(this.createCluster(neighbors));
      }
    }
  }
};

/**
 * @param {Array.<ol.Feature>} features Features
 * @return {ol.Feature} The cluster feature.
 * @protected
 */
_ol_source_Cluster_.prototype.createCluster = function (features) {
  var centroid = [0, 0];
  for (var i = features.length - 1; i >= 0; --i) {
    var geometry = this.geometryFunction(features[i]);
    if (geometry) {
      _coordinate2.default.add(centroid, geometry.getCoordinates());
    } else {
      features.splice(i, 1);
    }
  }
  _coordinate2.default.scale(centroid, 1 / features.length);

  var cluster = new _feature2.default(new _point2.default(centroid));
  cluster.set('features', features);
  return cluster;
};
exports.default = _ol_source_Cluster_;
module.exports = exports['default'];