/*  REC DALI 3.3.7 Polygon
In spherical coordinates, all longitude values must fall within [0,360] and
all latitude values within [-90,90]. Vertices must be ordered such that the
polygon winding direction is counter-clockwise (when viewed from the origin
toward the sky) as described in (Rots, 2007).


Rots, A. (2007), 'Space-time coordinate metadata for the virtual observa-
tory', IVOA Recommendation.
http://www.ivoa.net/documents/latest/STC.html :

4.5.1.4 Polygon
....
  In order to avoid ambiguities in direction, vertices need to be less
than 180 deg apart in both coordinates. Great circles or small circles spanning 180 deg
require specification of an extra intermediate vertex.
....
The boundaries are considered part of the region. The inside of the region is
defined as that part of coordinate space that is encircled by the polygon in a
counter-clockwise sense.
...
*/

class Polygon
{

   double[] lon;
   double[] lat;

   public Polygon(String value)
   {
      parsePolygon(value);
   }

   private void parsePolygon(String str)
   {
      String[] arr = str.strip().split(" +");

      if(arr == null)
         throw new IllegalArgumentException("POLYGON : no value, or value contains no space");
      else
      {
         final int minLen = 3*2; // REC SODA : at least 3 (lon,lat) points
         if(arr.length < minLen)
            throw new IllegalArgumentException(
                  "POLYGON : must have at least " + minLen + " elements delimited by space, but found " + arr.length);
         else
         {
            boolean isEven = ((arr.length % 2) == 0);
            if(!isEven)
               throw new IllegalArgumentException("POLYGON must have even number of values, but has " + arr.length);

            lon = new double[arr.length/2];
            lat = new double[arr.length/2];

            for(int ii=0; ii<(arr.length-1); ii+=2)
            {

               double dbl = Double.parseDouble(arr[ii]);
               if ((dbl < 0) || (dbl > 360))
                  throw new IllegalArgumentException("POLYGON : first number must be in range [0,360] but found " + dbl);
               else
                  this.lon[ii/2] = dbl;

               dbl = Double.parseDouble(arr[ii+1]);
               if ((dbl < -90) || (dbl > 90))
                  throw new IllegalArgumentException("POLYGON : second number must be in range [-90,90] but found " + dbl);
               else
                  this.lat[ii/2] = dbl;

            }

         }
      }
   }


   public String toString()
   {
      StringBuilder sb = new StringBuilder("POLYGON");
      int ii = 0;
      for(ii = 0; ii<lon.length; ii++)
         sb.append(" (" + String.valueOf(lon[ii]) + ", " + String.valueOf(lat[ii]) + ")");

      return sb.toString();
   }

}

