using System;
using Spherical;

/*=====================================================================

  File:      Rectangle.cs for Spatial Sample
  Summary:   Implements a simple region
  Date:	     August 16, 2005

---------------------------------------------------------------------
  This spatial search library was developed by Alexander Szalay, Robert Brunner, 
  Peter Kunszt, and Gyorgy Fekete at the Department of Physics and Astronomy, 
  The Johns Hopkins University, in collaboration with Jim Gray, Microsoft Research.
  Details of the algorithms can be found at http://www.sdss.jhu.edu/htm/.
 
======================================================= */

namespace Spherical.HTM
{
	/// <summary>
	/// Implements a simple region
	/// </summary>
	public class Rectangle  {
        public static Convex Make(double ra1, double dec1, double ra2, double dec2)
        {
            //
            // Create four halfspaces. Two great circles for RA and
            // two small circles for DEC

            double dlo, dhi; // offset from center, parameter for constraint
            double declo, dechi;
            double costh, sinth; // sine and cosine of theta (RA) for rotation of vector
            double x, y, z;

            //
            // Halfspaces belonging to declo and dechi are circles parallel
            // to the xy plane, their normal is (0, 0, +/-1)
            //
            // declo halfpsacet is pointing up (0, 0, 1)
            // dechi is pointing down (0, 0, -1)
            if (dec1 > dec2)
            {
                declo = dec2;
                dechi = dec1;
            }
            else
            {
                declo = dec1;
                dechi = dec2;
            }
            dlo = Math.Sin(declo * Const.Degree2Radian);
            dhi = -Math.Sin(dechi * Const.Degree2Radian); // Yes, MINUS!
            Convex con = new Convex(4);
            con.Add(new Halfspace(0.0, 0.0, 1.0, false, dlo)); // Halfspace #1
            con.Add(new Halfspace(0.0, 0.0, -1.0, false, dhi)); // Halfspace #1

            costh = Math.Cos(ra1 * Const.Degree2Radian);
            sinth = Math.Sin(ra1 * Const.Degree2Radian);
            x = -sinth;
            y = costh;
            z = 0.0;
            con.Add(new Halfspace(x, y, z, false, 0.0));// Halfspace #3

            costh = Math.Cos(ra2 * Const.Degree2Radian);
            sinth = Math.Sin(ra2 * Const.Degree2Radian);
            x = sinth;
            y = -costh;
            z = 0.0;

            con.Add(new Halfspace(x, y, z, false, 0.0));// Halfspace #4
            return con;
        }
	}
}
