package net.mar;
import javax.servlet.*;
import net.mar.AnException;
import net.mar.DefaultSelect;
import cds.Sesame;
import java.util.StringTokenizer;
import jsky.coords.*;
import java.awt.geom.*;


public class SQLRadial
{
		String ra2000=null;
		String dec2000=null;
		String sys=null;
				String ra=null;
				String dec=null;

				String radius="";
		String name=null;
	public String setRequest(ServletRequest req) throws AnException
	{

		String sql="";





   		String select=null;
     	String action=null;
      	String where=null;
      	String from=null;
      	int tableid=0;
		      if (req.getParameter("radius") != null)
		          {
		            radius = req.getParameter("radius");
		          }
		      if (req.getParameter("ra") != null)
		          {
		            ra = req.getParameter("ra");
		          }
		      if (req.getParameter("dec") != null)
		          {
		            dec = req.getParameter("dec");
		          }
		      if (req.getParameter("name") != null)
			      {
			        name = req.getParameter("name");
		          }
		      if (req.getParameter("sys") != null)
			      {
			        sys = req.getParameter("sys");
          		  }
      if (req.getParameter("select") != null)
	      {
	        select = req.getParameter("select");
          };
      if (req.getParameter("from") != null)
	      {
	        from = req.getParameter("from");
          };
      if (req.getParameter("where") != null)
	      {
	        where = req.getParameter("where");
          };

     if (ra.length() > 0 & dec.length() > 0 & name.length() > 0)
      {
		  throw new AnException("Only supply coordinates OR name");
        }
     if (select.length() ==0 || select.equals("") || select==null)
       {
		    throw new AnException("please enter some parameters in Select box");
        }

       if (radius == null || radius.equals("")){
	           throw new AnException("No radius supplied.");
	        }

		try {
			  if (Float.parseFloat(radius) > 90)
			  {
				  throw new AnException("Radius supplied should be less than 90 arcmin");
			   }
		   }
	       catch (NumberFormatException e)
	            {
					throw new AnException("Radius supplied was not a number");
            };




       if (name.length() > 0){
			  sys="J";
			  String result = null;
			  try {
			  Sesame sesame = new Sesame();
		      result = sesame.getNameResolved(name);
		  	  }
		  	  catch (Exception e){
				  throw new AnException("Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
						  }
		      if (result == null)
		      {
				 throw new AnException("Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
					}


		      String sub = result.substring(result.indexOf("%J")+2,result.indexOf("(",result.indexOf("%J")));
		      sub=sub.trim();
		      StringTokenizer st = new StringTokenizer(sub);
		      ra=st.nextToken();
		      dec=st.nextToken();
		      double raValue=-100;
		      double decValue=-100;
		      try
		  	    {
		  	      raValue = Double.parseDouble(ra);
		  	      decValue = Double.parseDouble(dec);
		  	    }
		  	    catch (NumberFormatException nfe)
		  	    {
					throw new AnException("Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
		      }

		      if (raValue > 360 || raValue < 0 || decValue < -90 || decValue > 90)
		      {
				  throw new AnException("Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
		   		}
			}
         else {
			     if (ra == null || ra.equals("") || dec==null || dec.equals("")){
					throw new AnException("Check values of supplied coords (blank or null).");
			 }
			 }

	 WorldCoords wc =new WorldCoords();
try {
wc = new WorldCoords(Double.parseDouble(ra),Double.parseDouble(dec));
}
catch (Exception e){
	try {
		wc = new WorldCoords(ra,dec);
	}
	catch (Exception ane) {
		throw new AnException("Check values of supplied coords.");
			 }
		 }

Point2D.Double point=new Point2D.Double(wc.getX(),wc.getY());
wcscon wcs=new wcscon();
if (sys.equals("G")){
wcs.gal2fk5(point);
}
if (sys.equals("B")){
wcs.fk425(point);
}
ra2000=String.valueOf(point.getX());
dec2000=String.valueOf(point.getY());

ra2000=ra2000.replace('+',' ');
dec2000=dec2000.replace('+',' ');
DefaultSelect ds = new DefaultSelect();
       if (from.equalsIgnoreCase("source"))
       {
		   select=SQLRadial.replaceall(select,"default",ds.getDefault("source"));
		   tableid=1;
	   }
	   else
	   {   select=SQLRadial.replaceall(select,"default",ds.getDefault("detection"));
		   tableid=3;
	   }


       if (where != null && !where.equals("") && !where.equals(" "))
       {
       sql="SELECT  "+ select +
       " FROM " + from + " inner join fGetNearbyObjEq("+
       ra2000 +","+ dec2000 +","+ radius + " , "+tableid+ ")  as n on n.objID="+from+".objID " +
       " where "+ where ;
   		}
   		else {
			sql="SELECT  "+ select +
	       " FROM " + from + " inner join fGetNearbyObjEq("+
	       ra2000 +","+ dec2000 +","+ radius + " , "+tableid+ ")  as n on n.objID="+from+".objID ";
		}
//EXEC dbo.spWebExecuteSQL ' + " '"
return sql;
	}

	public String getRA()
	{
		return ra;
	}
	public String getDec()
	{
		return dec;
	}
	public String getSys()
	{
		return sys;
	}
	public String getRadius()
	{
		return radius;
	}

	   public static String replaceall (String orig, String from, String to)
	    {
	        int fromLength = from.length();

	        if (fromLength==0)
	            throw new IllegalArgumentException
	            ("String to be replaced must not be empty");

	        int start = orig.indexOf (from);
	        if (start==-1)
	            return orig;

	        boolean greaterLength = (to.length() >= fromLength);

	        StringBuffer buffer;
	        // If the "to" parameter is longer than (or
	        // as long as) "from", the final length will
	        // be at least as large
	        if (greaterLength)
	        {
	            if (from.equals (to))
	                return orig;
	            buffer = new StringBuffer(orig.length());
	        }
	        else
	        {
	            buffer = new StringBuffer();
	        }

	        char [] origChars = orig.toCharArray();

	        int copyFrom=0;
	        while (start != -1)
	        {
	            buffer.append (origChars, copyFrom, start-copyFrom);
	            buffer.append (to);
	            copyFrom=start+fromLength;
	            start = orig.indexOf (from, copyFrom);
	        }
	        buffer.append (origChars, copyFrom, origChars.length-copyFrom);

	        return buffer.toString();
	    }

}