package yi.graph.polygon.gpc;

import yi.graph.polygon.*;

/**
 * Polygon set structure
 */

public class GpcPolygon {

  public int[] holes;            // Hole / external contour flags
  public GpcContour[] contours;  // Contour array

  public GpcPolygon() {
  }

  public GpcPolygon(int[] holes, GpcContour[] contours) {
    this.holes = holes;
    this.contours = contours;
  }

  /**
   * Init a simple GpcPolygon having only one contour
   * @param contour
   */
  public GpcPolygon(GpcContour contour) {
    contours = new GpcContour[]{contour};
    holes = new int[]{0};
  }

  public GpcPolygon(GenericContour poly) {
    this(new GpcContour(poly));
  }

  /**
   * Construct GpcPolygon from GenericPolygon.  Use SHALLOW copy to accerate the
   * speed.
   * @param poly
   */
  public GpcPolygon(GenericPolygon poly) {
    int n = poly.getContourNum();
    holes = new int[n];
    contours = new  GpcContour[n];
    for (int i=0; i<n; i++) {
      holes[i] = poly.holes[i]? 1: 0;
      contours[i] = new GpcContour(poly.contours[i]);
    }
  }


  public int getContourNum() {
    return (contours==null)? 0: contours.length;
  }

  public double getArea() {
    int contour_num = getContourNum();
    double area = 0;
    for (int i=0; i<contour_num; i++) {
      if (holes[i] == 0) { // not hole
        area += contours[i].getArea();
      } else { // hole
        area -= contours[i].getArea();
      }
    }
    return area;
  }


  public String toString() {
    StringBuffer buffer = new StringBuffer();

    int num_contours = (contours == null)? 0: contours.length;

    // number of contours
    buffer.append(num_contours);
    buffer.append("\n");

    for (int c = 0; c < num_contours; c++) {
      GpcContour contour = contours[c];
      int num_vertices = (contour.x == null)? 0: contour.x.length;

      // number of vertices
      buffer.append(num_vertices);
      buffer.append("\n");

      // hole flag
      buffer.append(holes[c]);
      buffer.append("\n");

      // vertices
      for (int v = 0; v < num_vertices; v++) {
        buffer.append(" ");
        buffer.append(contour.x[v]);
        buffer.append(" ");
        buffer.append(contour.y[v]);
        buffer.append("\n");
      }
    }

    return buffer.toString();
  }
}