package util;

import visad.*;
import visad.data.hdfeos.LambertAzimuthalEqualArea;
import visad.georef.MapProjection;
import java.awt.geom.Rectangle2D;
import java.lang.Math;


public class LambertEA extends MapProjection
{
   CoordinateSystem cs = null;
   Rectangle2D rect    = null;
   int lon_idx = 0;
   int lat_idx = 1;

   public LambertEA(float[][] corners) 
          throws Exception {
     this(corners, 6367470, 0, 0);
   }

   public LambertEA(float[][] corners,
                    float earthRadius, 
                    float false_easting,
                    float false_northing)
          throws Exception 
   {
     super(RealTupleType.SpatialEarth2DTuple, null);

     float[] minmaxLon = Helper.minmax(corners[0]);
     float[] minmaxLat = Helper.minmax(corners[1]);
     float minLon = minmaxLon[0];
     float minLat = minmaxLat[0];
     float maxLon = minmaxLon[1];
     float maxLat = minmaxLat[1];

     float londiff = maxLon - minLon;
     float lonCenter = minLon + londiff/2;
     if (londiff > 180) lonCenter += 180;
     float latCenter = minLat + (maxLat - minLat)/2;

     cs = new LambertAzimuthalEqualArea(getReference(), earthRadius, 
                                    lonCenter*Data.DEGREES_TO_RADIANS,
                                    latCenter*Data.DEGREES_TO_RADIANS,
                                    false_easting, false_northing);

     float[][] cs_corners = cs.fromReference(new float[][] {corners[lon_idx], corners[lat_idx]});

     float[] minmax_x = Helper.minmax(cs_corners[lon_idx]);
     float[] minmax_y = Helper.minmax(cs_corners[lat_idx]);
     float min_x = minmax_x[0];
     float min_y = minmax_y[0];
     float max_x = minmax_x[1];
     float max_y = minmax_y[1];

     rect = new Rectangle2D.Float(min_x, min_y, (max_x - min_x), (max_y - min_y));
   }

   public Rectangle2D getDefaultMapArea() {
     return rect;
   }

   public boolean equals(Object cs) {
     return false;
   }

   public float[][] fromRefernece(float[][] values) 
          throws VisADException {
     return cs.fromReference(values);
   }
 
   public float[][] toReference(float[][] values)
          throws VisADException {
     return cs.toReference(values);
   }

   public double[][] fromReference(double[][] values) 
          throws VisADException {
     return cs.fromReference(values);
   }

   public double[][] toReference(double[][] values) 
          throws VisADException {
     return cs.toReference(values);
   }
}
