"use strict";

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

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

var THREE = _interopRequireWildcard(require("three"));

var _LayerUpdateState = _interopRequireDefault(require("../Layer/LayerUpdateState"));

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

var _handlerNodeError = _interopRequireDefault(require("./handlerNodeError"));

var _Coordinates = _interopRequireDefault(require("../Core/Geographic/Coordinates"));

function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function () {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

var coord = new _Coordinates["default"]('EPSG:4326', 0, 0, 0);
var mat4 = new THREE.Matrix4();

function applyMatrix4(obj, mat4) {
  if (obj.geometry) {
    obj.geometry.applyMatrix4(mat4);
  }

  obj.children.forEach(function (c) {
    return applyMatrix4(c, mat4);
  });
}

function assignLayer(object, layer) {
  if (object) {
    object.layer = layer;

    if (object.material) {
      object.material.transparent = layer.opacity < 1.0;
      object.material.opacity = layer.opacity;
      object.material.wireframe = layer.wireframe;

      if (layer.size) {
        object.material.size = layer.size;
      }

      if (layer.linewidth) {
        object.material.linewidth = layer.linewidth;
      }
    }

    object.layers.set(layer.threejsLayer);

    var _iterator = _createForOfIteratorHelper(object.children),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var c = _step.value;
        assignLayer(c, layer);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return object;
  }
}

function extentInsideSource(extent, source) {
  return !source.extentInsideLimit(extent) || source.isFileSource && !extent.isPointInside(source.extent.center(coord));
}

var _default = {
  update: function update(context, layer, node) {
    if (!node.parent && node.children.length) {
      // if node has been removed dispose three.js resource
      _ObjectRemovalHelper["default"].removeChildrenAndCleanupRecursively(layer, node);

      return;
    }

    if (!node.visible) {
      return;
    }

    if (node.layerUpdateState[layer.id] === undefined) {
      node.layerUpdateState[layer.id] = new _LayerUpdateState["default"]();
    }

    if (!node.layerUpdateState[layer.id].canTryUpdate()) {
      return;
    }

    var features = node.children.filter(function (n) {
      return n.layer == layer;
    });

    if (features.length > 0) {
      return features;
    }

    var extentsDestination = node.getExtentsByProjection(layer.source.projection) || [node.extent];
    var extentsSource = [];

    var _iterator2 = _createForOfIteratorHelper(extentsDestination),
        _step2;

    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var extentDest = _step2.value;
        var ext = layer.source.projection == extentDest.crs ? extentDest : extentDest.as(layer.source.projection);
        ext.zoom = extentDest.zoom;

        if (extentInsideSource(ext, layer.source)) {
          node.layerUpdateState[layer.id].noMoreUpdatePossible();
          return;
        }

        extentsSource.push(extentDest);
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }

    node.layerUpdateState[layer.id].newTry();
    var command = {
      layer: layer,
      extentsSource: extentsSource,
      view: context.view,
      threejsLayer: layer.threejsLayer,
      requester: node
    };
    return context.scheduler.execute(command).then(function (result) {
      // if request return empty json, WFSProvider.getFeatures return undefined
      result = result[0];

      if (result) {
        var isApplied = !result.layer;
        assignLayer(result, layer); // call onMeshCreated callback if needed

        if (layer.onMeshCreated) {
          layer.onMeshCreated(result);
        }

        node.layerUpdateState[layer.id].success();

        if (!node.parent) {
          _ObjectRemovalHelper["default"].removeChildrenAndCleanupRecursively(layer, result);

          return;
        } // We don't use node.matrixWorld here, because feature coordinates are
        // expressed in crs coordinates (which may be different than world coordinates,
        // if node's layer is attached to an Object with a non-identity transformation)


        if (isApplied) {
          // NOTE: now data source provider use cache on Mesh
          // TODO move transform in feature2Mesh
          mat4.copy(node.matrixWorld).getInverse(mat4).elements[14] -= result.minAltitude;
          applyMatrix4(result, mat4);
        }

        if (result.minAltitude) {
          result.position.z = result.minAltitude;
        }

        result.layer = layer;
        node.add(result);
        node.updateMatrixWorld();
      } else {
        node.layerUpdateState[layer.id].failure(1, true);
      }
    }, function (err) {
      return (0, _handlerNodeError["default"])(err, node, layer, node.level, context.view);
    });
  }
};
exports["default"] = _default;