
// Fixer.java
// Martin Davis
// The LocationTech Technology (LTT) Group; Vivid Solutions
// https://github.com/locationtech/jts
// Modified by Andrew Davison, ad@coe.psu.ac.th, March 2023

/* Three examples using the GeometryFixer class.
   An invalid geometry is made valid by being split into parts
   or by reorganization of the coordinates.

   When a shape is split into parts, this can be seen in GeomsViewer by
   the different colors for each part.

   Usage:
    > compile Fixer.java
    > run Fixer

  When prompted, press <enter> on the command line to move 
  to the next example.
*/

import java.util.*;

import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.util.GeometryFixer;



public class Fixer
{
  private static GeomsViewer gv;


  public static void main(String[] args)
  {
    gv = Utils.view("Fixer");

    calcFix("bowtie", "POLYGON ((110 190, 190 110, 190 190, 110 110, 110 190))");

    calcFix("Overlaps",
          "POLYGON ((110 190, 150 190, 150 130, 170 130, 170 150, 130 150, 130 170, 190 170, 190 110, 110 110, 110 190))");

    calcFix("Touching Holes",
          "POLYGON ((100 100, 100 175, 190 175, 190 100, 100 100), (145 115, 160 115, 160 130, 145 130, 145 115), (145 130, 115 160, 175 160, 160 130, 160 145, 145 130, 130 145, 145 130))");

    gv.close();
  } /* main */


  private static void calcFix(String title, String wtk)
  {
    Geometry geom = Utils.toGeometry(wtk);

    gv.clear();
    gv.setTitle(title);
    System.out.println("--- " + title + " ---");
    gv.add(geom);
    System.out.println("\nGeometry: " + geom);
    System.out.println("Geometry is valid: " + geom.isValid());
    Utils.pause(1000);

    GeometryFixer fixer = new GeometryFixer(geom);
    Geometry fix = fixer.getResult();
    System.out.println("\nFix: " + fix);
    System.out.println("Fix is valid: " + fix.isValid());

    if (fix instanceof MultiPolygon) {
      int count = fix.getNumGeometries();
      // extract each polygon and display separately
      System.out.println("Polygon parts:");
      for(int i = 0; i < count; i++) {
        Geometry poly = fix.getGeometryN(i);
        gv.add(poly);
        System.out.println(" " + (i+1) + ". " + poly);
      }
    }
    else
     gv.add(fix);

    Utils.waitEnter();
  }  // end of calcFix()

 
} // end of Fixer class
