"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _Layer2 = _interopRequireDefault(require("./Layer"));

var _Picking = _interopRequireDefault(require("../Core/Picking"));

var _Cache = require("../Core/Scheduler/Cache");

var _ObjectRemovalHelper = _interopRequireDefault(require("../Process/ObjectRemovalHelper"));

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

/**
 * Fires when the opacity of the layer has changed.
 * @event GeometryLayer#opacity-property-changed
 */

/**
 * @property {boolean} isGeometryLayer - Used to checkout whether this layer is
 * a GeometryLayer. Default is true. You should not change this, as it is used
 * internally for optimisation.
 * @property {number} [zoom.max=Infinity] - this is the maximum zoom beyond which it'll be hidden.
 * The `max` is constant and the value is `Infinity` because there's no maximum display level after which it is hidden.
 * This property is used only if the layer is attached to [TiledGeometryLayer]{@link TiledGeometryLayer}.
 * @property {number} [zoom.min=0] - this is the minimum zoom from which it'll be visible.
 * This property is used only if the layer is attached to [TiledGeometryLayer]{@link TiledGeometryLayer}.
 */
var GeometryLayer = /*#__PURE__*/function (_Layer) {
  (0, _inherits2["default"])(GeometryLayer, _Layer);

  var _super = _createSuper(GeometryLayer);

  /**
   * A layer usually managing a geometry to display on a view. For example, it
   * can be a layer of buildings extruded from a a WFS stream.
   *
   * @constructor
   * @extends Layer
   *
   * @param {string} id - The id of the layer, that should be unique. It is
   * not mandatory, but an error will be emitted if this layer is added a
   * {@link View} that already has a layer going by that id.
   * @param {THREE.Object3D} object3d - The object3D used to contain the
   * geometry of the GeometryLayer. It is usually a `THREE.Group`, but it can
   * be anything inheriting from a `THREE.Object3D`.
   * @param {Object} [config] - Optional configuration, all elements in it
   * will be merged as is in the layer. For example, if the configuration
   * contains three elements `name, protocol, extent`, these elements will be
   * available using `layer.name` or something else depending on the property
   * name.
   * @param {Source} [config.source] - Description and options of the source.
   *
   * @throws {Error} `object3d` must be a valid `THREE.Object3d`.
   *
   * @example
   * // Create a GeometryLayer
   * const geometry = new GeometryLayer('buildings', new THREE.Object3D(), {
   *      source: {
   *          url: 'http://server.geo/wfs?',
   *          protocol: 'wfs',
   *          format: 'application/json'
   *      },
   * });
   *
   * // Add the layer
   * view.addLayer(geometry);
   */
  function GeometryLayer(id, object3d) {
    var _config$cacheLifeTime;

    var _this;

    var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    (0, _classCallCheck2["default"])(this, GeometryLayer);
    config.cacheLifeTime = (_config$cacheLifeTime = config.cacheLifeTime) !== null && _config$cacheLifeTime !== void 0 ? _config$cacheLifeTime : _Cache.CACHE_POLICIES.GEOMETRY; // Remove this part when Object.assign(this, config) will be removed from Layer Constructor

    var visible = config.visible;
    delete config.visible;
    _this = _super.call(this, id, config);
    _this.isGeometryLayer = true;

    if (!object3d || !object3d.isObject3D) {
      throw new Error("Missing/Invalid object3d parameter (must be a\n                three.js Object3D instance)");
    }

    if (object3d.type === 'Group' && object3d.name === '') {
      object3d.name = id;
    }

    Object.defineProperty((0, _assertThisInitialized2["default"])(_this), 'object3d', {
      value: object3d,
      writable: false,
      configurable: true
    });
    _this.opacity = 1.0;
    _this.wireframe = false;
    _this.attachedLayers = [];
    _this.visible = visible !== null && visible !== void 0 ? visible : true;
    Object.defineProperty(_this.zoom, 'max', {
      value: Infinity,
      writable: false
    }); // Feature options

    _this.filteringExtent = !_this.source.isFileSource;
    _this.structure = '3d';
    return _this;
  }

  (0, _createClass2["default"])(GeometryLayer, [{
    key: "visible",
    get: function get() {
      return this.object3d.visible;
    },
    set: function set(value) {
      if (this.object3d.visible !== value) {
        var event = {
          type: 'visible-property-changed',
          previous: {},
          "new": {}
        };
        event.previous.visible = this.object3d.visible;
        event["new"].visible = value;
        this.dispatchEvent(event);
        this.object3d.visible = value;
      }
    } // Attached layers expect to receive the visual representation of a
    // layer (= THREE object with a material).  So if a layer's update
    // function don't process this kind of object, the layer must provide a
    // getObjectToUpdateForAttachedLayers function that returns the correct
    // object to update for attached layer.
    // See 3dtilesLayer or PotreeLayer for examples.
    // eslint-disable-next-line arrow-body-style

  }, {
    key: "getObjectToUpdateForAttachedLayers",
    value: function getObjectToUpdateForAttachedLayers(obj) {
      if (obj.parent && obj.material) {
        return {
          element: obj,
          parent: obj.parent
        };
      }
    } // Placeholder
    // eslint-disable-next-line

  }, {
    key: "postUpdate",
    value: function postUpdate() {} // Placeholder
    // eslint-disable-next-line

  }, {
    key: "culling",
    value: function culling() {
      return true;
    }
    /**
     * Attach another layer to this one. Layers attached to a GeometryLayer will
     * be available in `geometryLayer.attachedLayers`.
     *
     * @param {Layer} layer - The layer to attach, that must have an `update`
     * method.
     */

  }, {
    key: "attach",
    value: function attach(layer) {
      if (!layer.update) {
        throw new Error("Missing 'update' function -> can't attach layer\n                ".concat(layer.id));
      }

      this.attachedLayers.push(layer); // To traverse GeometryLayer object3d attached

      layer.parent = this;
    }
    /**
     * Detach a layer attached to this one. See {@link attach} to learn how to
     * attach a layer.
     *
     * @param {Layer} layer - The layer to detach.
     *
     * @return {boolean} Confirmation of the detachment of the layer.
     */

  }, {
    key: "detach",
    value: function detach(layer) {
      var count = this.attachedLayers.length;
      this.attachedLayers = this.attachedLayers.filter(function (attached) {
        return attached.id != layer.id;
      });
      layer.parent = undefined;
      return this.attachedLayers.length < count;
    }
    /**
     * All layer's 3D objects are removed from the scene and disposed from the video device.
     * @param {boolean} [clearCache=false] Whether to clear the layer cache or not
     */

  }, {
    key: "delete",
    value: function _delete(clearCache) {
      if (clearCache) {
        this.cache.clear();
      } // if Layer is attached


      if (this.parent) {
        _ObjectRemovalHelper["default"].removeChildrenAndCleanupRecursively(this, this.parent.object3d);
      }

      if (this.object3d.parent) {
        this.object3d.parent.remove(this.object3d);
      }

      _ObjectRemovalHelper["default"].removeChildrenAndCleanupRecursively(this, this.object3d);
    }
    /**
     * Picking method for this layer. It uses the {@link Picking#pickObjectsAt}
     * method.
     *
     * @param {View} view - The view instance.
     * @param {Object} coordinates - The coordinates to pick in the view. It
     * should have at least `x` and `y` properties.
     * @param {number} radius - Radius of the picking circle.
     * @param {Array} target - target to push result.
     *
     * @return {Array} An array containing all targets picked under the
     * specified coordinates.
     */

  }, {
    key: "pickObjectsAt",
    value: function pickObjectsAt(view, coordinates) {
      var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.options.defaultPickingRadius;
      var target = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
      return _Picking["default"].pickObjectsAt(view, coordinates, radius, this.object3d, target);
    }
  }]);
  return GeometryLayer;
}(_Layer2["default"]);

var _default = GeometryLayer;
exports["default"] = _default;