Source: tools/services/featureUnion.js

import GeoJSON from 'ol/format/GeoJSON'
import turfUnion from '@turf/union'

// TODO gérer les projection, notre carte par défaut est en EPSG:3857, ce qui est parfait pour turf

function buildUnion (features) {
  const geojsonReader = new GeoJSON()

  const feature = features.reduce((acc, feature) => {
    const jsonFeature = geojsonReader.writeFeatureObject(feature)
    if (acc === null) {
      return jsonFeature
    }
    return turfUnion(acc, jsonFeature)
  }, null)
  return feature
}

/**
 * Est-ce que ces features peuvent avoir une union?
 * @param {Array<Feature>} features
 * @returns Boolean
 */
function isUnionPossible (features, contiguonsPolygon = false) {
  if (!features || features.length < 2) {
    return false
  }

  const feature = buildUnion(features)
  return contiguonsPolygon
    ? feature.geometry.type === 'Polygon'
    : true
}

/**
 * Effectue l'union de feature
 * @param {Array<Feature>} features
 * @returns ol-feature
 */
function union (features) {
  const jsonFeature = buildUnion(features)
  const geojsonReader = new GeoJSON()
  return geojsonReader.readFeature(jsonFeature)
}

export const FeatureUnion = {
  isUnionPossible,
  union,
}