import getFillTemplate from './getFillTemplate.js';
import Shape from 'Doodle3D/clipper-js';
import { PRECISION } from '../constants.js';

export default function generateSupport(slices, settings) {
  if (!settings.support.enabled) return;

  let {
    layerHeight,
    support: {
      gridSize: supportGridSize,
      margin: supportMargin,
      plateSize: plateSize,
      distanceY: supportDistanceY
    },
    nozzleDiameter
  } = settings;

  supportGridSize /= PRECISION;
  supportMargin /= PRECISION;
  plateSize /= PRECISION;
  nozzleDiameter /= PRECISION;
  var supportDistanceLayers = Math.max(Math.ceil(supportDistanceY / layerHeight), 1);

  var supportAreas = new Shape([], true);

  for (var layer = slices.length - 1 - supportDistanceLayers; layer >= 0; layer --) {
    var currentSlice = slices[layer];

    if (supportAreas.length > 0) {

      if (layer >= supportDistanceLayers) {
        var sliceSkin = slices[layer - supportDistanceLayers].outline;
        sliceSkin = sliceSkin;

        var supportAreasSlimmed = supportAreas.difference(sliceSkin.offset(supportMargin));
        if (supportAreasSlimmed.area() < 100.0) {
          supportAreas = supportAreas.difference(sliceSkin);
        }
        else {
          supportAreas = supportAreasSlimmed;
        }
      }

      var supportTemplate = getFillTemplate(supportAreas.bounds(), supportGridSize, true, true);
      var supportFill = supportTemplate.intersect(supportAreas);
      if (supportFill.length === 0) {
        currentSlice.support = supportAreas.clone();
      }
      else {
        currentSlice.support = supportFill;
      }
    }

    var supportSkin = slices[layer + supportDistanceLayers - 1].outline;

    var slice = slices[layer + supportDistanceLayers];
    for (var i = 0; i < slice.parts.length; i ++) {
      var slicePart = slice.parts[i];

      if (slicePart.intersect.closed) {
        var outerLine = slicePart.outerLine;
      }
      else {
        var outerLine = slicePart.intersect.offset(supportMargin);
      }

      var overlap = supportSkin.offset(supportMargin).intersect(outerLine);
      var overhang = outerLine.difference(overlap);

      if (overlap.length === 0 || overhang.length > 0) {
        supportAreas = supportAreas.join(overhang);
      }
    }
  }
}
