"use strict";

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

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

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

function isValidData(data, extentDestination, validFn) {
  if (data && (!validFn || validFn(data, extentDestination))) {
    return data;
  }
}

var error = function (err, source) {
  source.handlingError(err);
  throw err;
};

function parseSourceData(data, extDest, layer) {
  var source = layer.source;
  var options = {
    buildExtent: source.isFileSource || !layer.isGeometryLayer,
    crsIn: source.projection,
    crsOut: layer.projection,
    // TODO FIXME: error in filtering vector tile
    // filteringExtent: extentDestination.as(layer.projection),
    filteringExtent: !source.isFileSource && layer.isGeometryLayer ? extDest.as(source.projection) : undefined,
    overrideAltitudeInToZero: layer.overrideAltitudeInToZero,
    filter: layer.filter || source.filter,
    isInverted: source.isInverted,
    mergeFeatures: layer.mergeFeatures === undefined ? true : layer.mergeFeatures,
    withNormal: layer.isGeometryLayer !== undefined,
    withAltitude: layer.isGeometryLayer !== undefined,
    layers: source.layers
  };
  return source.parser(data, options).then(function (parsedFile) {
    return source.onParsedFile(parsedFile);
  });
}

function fetchSourceData(extSrc, layer) {
  var source = layer.source; // If source, we must fetch and convert data
  // URL of the resource you want to fetch

  var url = source.urlFromExtent(extSrc); // Fetch data

  return source.fetcher(url, source.networkOptions).then(function (f) {
    f.extent = extSrc;
    return f;
  });
}

var _default = {
  executeCommand: function executeCommand(command) {
    var promises = [];
    var layer = command.layer;
    var source = layer.source;
    var extentsSource = command.extentsSource;
    var extentsDestination = command.extentsDestination || extentsSource;
    var parsedData = command.parsedData || [];

    for (var i = 0, max = extentsSource.length; i < max; i++) {
      var extSource = extentsSource[i]; // Tag to Cache data

      var exTag = source.isVectorSource ? extentsDestination[i] : extSource; // Get converted source data, in cache

      var convertedSourceData = _Cache["default"].get(source.uid, layer.id, exTag.toString('-')); // If data isn't in cache


      if (!convertedSourceData) {
        (function () {
          var extDest = extentsDestination[i]; // Already fetched and parsed data that can be used

          var validedParsedData = isValidData(parsedData[i], extDest, layer.isValidData) || source.parsedData;

          if (validedParsedData) {
            // Convert
            convertedSourceData = layer.convert(validedParsedData, extDest, layer);
          } else if (source.fetchedData) {
            // Parse and convert
            convertedSourceData = parseSourceData(source.fetchedData, extDest, layer).then(function (parsedData) {
              return layer.convert(parsedData, extDest, layer);
            }, function (err) {
              return error(err, source);
            });
          } else {
            // Fetch, parse and convert
            convertedSourceData = fetchSourceData(extSource, layer).then(function (fetchedData) {
              return parseSourceData(fetchedData, extDest, layer);
            }, function (err) {
              return error(err, source);
            }).then(function (parsedData) {
              return layer.convert(parsedData, extDest, layer);
            }, function (err) {
              return error(err, source);
            });
          } // Put converted data in cache


          _Cache["default"].set(convertedSourceData, _Cache["default"].POLICIES.TEXTURE, source.uid, layer.id, exTag.toString('-'));
        })();
      } // Verify some command is resolved
      // See old WFSProvider : command.resolve(result)


      promises.push(convertedSourceData);
    }

    return Promise.all(promises);
  }
};
exports["default"] = _default;