package uk.ac.roe.wfau;

import java.awt.geom.Point2D;
import java.util.StringTokenizer;

import javax.servlet.ServletRequest;

import jsky.coords.WorldCoords;
import jsky.coords.wcscon;

//import cds.Sesame;


import net.mar.AnException;

/**
 * This class parses the parameters supplied via the user interface.
 * 
 * @author mar
 * @version 1.0
 * 
 * 
 *  
 */
public class SQLRegion {
    /** maximum radius for search in arcmin */
    static float maxRadius = 90;

    /** maximum xSize for search in arcmin */
    static float maxX = 60;

    /** maximum ySize for search in arcmin */
    static float maxY = 60;

    /** J2000 RA */
    String ra2000 = null;

    /** J2000 Dec */
    String dec2000 = null;

    /** longitude */
    String longitude = null;

    /** latitude */
    String latitude = null;
    
    /** coordinate system */
    String sys = null;

    /** User supplied longitude */
    String ra = null;

    /** User supplied latitude */
    String dec = null;

    /** User supplied object name (simbad) */
    String name = null;

    /** User supplied radius arcmin */
    String radius = "";

    /** User supplied longitude xsize arcmin */
    String xSize = "";

    /** User supplied latitude ysize arcmin */
    String ySize = "";

    /**
     * @param req
     *            the servlet request containing the user parameters
     * @return SQL statement
     * @throws AnException
     */

    public String setRequest(ServletRequest req) throws AnException {
        String sql = "sql";
        StringBuffer errorBuffer = new StringBuffer("");
        boolean errors = false;
        String select = null;
        String action = null;
        String where = null;
        String from = null;
        action = req.getParameter("action");
        radius = req.getParameter("radius");
        xSize = req.getParameter("xSize");
        ySize = req.getParameter("ySize");

        ra = req.getParameter("ra");
        dec = req.getParameter("dec");
        name = req.getParameter("name");
        sys = req.getParameter("sys");
        select = req.getParameter("select");
        from = req.getParameter("from");
        where = req.getParameter("where");
        try {
            if (!action.equals("radial") && !action.equals("box")) {
                errors = true;
                errorBuffer.append(" Invalid action supplied.");
            }
        }

        catch (Exception e) {
            errors = true;
            errorBuffer.append(" Invalid action supplied.");
        }
        try {
            if (action.equals("radial")) {
                try {
                    if (Float.parseFloat(radius) > maxRadius
                            || Float.parseFloat(radius) < 0) {
                        errors = true;
                        errorBuffer.append(" Radius should be > 0 and < "
                                + maxRadius + " arcmin.");
                    }
                } catch (Exception e) {
                    errors = true;
                    errorBuffer.append(" Invalid radius");
                }
            }
        } catch (Exception e) {
            // not a radial query
        }
        try {
            if (action.equals("box")) {
                try {
                    if (Float.parseFloat(xSize) > maxX
                            || Float.parseFloat(xSize) < 0
                            || Float.parseFloat(ySize) > maxY
                            || Float.parseFloat(ySize) < 0) {
                        errors = true;
                        errorBuffer.append(" X-size should be > 0 and < "
                                + maxX + " arcmin.");
                        errorBuffer.append(" Y-size should be > 0 and < "
                                + maxY + " arcmin.");
                    }
                } catch (Exception e) {
                    errors = true;
                    errorBuffer.append(" Invalid box size");
                }
            }
        } catch (Exception e) {
            // not a box query
        }
        if (ra.length() > 0 & dec.length() > 0 & name.length() > 0) {
            errors = true;
            errorBuffer.append(" Only supply coordinates OR name");
        }
        if (name.length() > 0) {
            sys = "J";
            String result = null;
            try {
                Sesame sesame = new Sesame();
                result = sesame.getNameResolved(name);
            } catch (Exception e) {
                errors = true;
                errorBuffer
                        .append(" Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
            }
            if (result == null) {
                errors = true;
                errorBuffer
                        .append("  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);
                if (raValue > 360 || raValue < 0 || decValue < -90
                        || decValue > 90) {
                    errors = true;
                    errorBuffer
                            .append(" Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
                }
            } catch (NumberFormatException nfe) {
                errors = true;
                errorBuffer
                        .append(" Unable to resolve supplied name into valid RA & Dec. Please try later or input coords directly.");
            }

        } else
        //  no name supplied
        {
            if (ra == null || ra.equals("") || dec == null || dec.equals("")) {
                errors = true;
                errorBuffer
                        .append(" Check values of supplied coordinates (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 ee) {
                errors = true;
                errorBuffer
                        .append(" Unable to parse coordinates.");
            }
        }
        longitude=String.valueOf(wc.getX());
        latitude=String.valueOf(wc.getY());
        
        Point2D.Double point = new Point2D.Double(wc.getX(), wc.getY());
       // wcscon wcs = new wcscon();
        if (sys.equals("G")) {
            wcscon.gal2fk5(point);
        }
        if (sys.equals("B")) {
            wcscon.fk425(point);
        }
        ra2000 = String.valueOf(point.getX());
        dec2000 = String.valueOf(point.getY());

        ra2000 = ra2000.replace('+', ' ');
        dec2000 = dec2000.replace('+', ' ');
        System.out.println("lon "+longitude+" lat "+latitude+" ra2000 "+ra2000+" dec2000 "+dec2000);
        if (errors == true) {
            throw new AnException(errorBuffer.toString());
        }

        return sql;

    }
}