import difference from '@turf/difference'
import { feature, multiPolygon, polygon, featureCollection, multiPoint } from '@turf/helpers'
import { getGeom } from '@turf/invariant'
import { flattenEach, featureEach } from '@turf/meta'

import simplepolygon from 'simplepolygon'
import gpsi from 'geojson-polygon-self-intersections'

export function unkinkPolygon (geojson) {
  const features = []
  const holes = []

  flattenEach(geojson, feature => {
    if (feature.geometry.type !== 'Polygon') return
    const isects = gpsi(feature, val => val)
    if (isects.length < 1) return features.push(feature) // don't run it through simple polygon if it's not really intersecting

    // remove the holes and set them aside for later
    const holeCoords = feature.geometry.coordinates.splice(1, feature.geometry.coordinates.length - 1)
    if (holeCoords.length > 0) holes.push(multiPolygon(holeCoords.map(c => [c])))

    featureEach(simplepolygon(feature), poly => {
      const newPoly = polygon(poly.geometry.coordinates, feature.properties)
      features.push(newPoly)
    })
  })

  // punch the holes back out of the feature
  const fixedFeatures = holes.length > 0 ? features.map(feature => {
    return holes.reduce((accumulator, hole) => difference(accumulator, hole), feature)
  }) : features
  return featureCollection(fixedFeatures)
}

export function kinks (geojson) {
  const coordinates = []
  flattenEach(geojson, function (feature) {
    if (feature.geometry.type !== 'Polygon') return
    gpsi(feature, isect => { coordinates.push(isect) })
  })
  return multiPoint(coordinates)
}