/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sample.scatterplot.restful;

import sample.scatterplot.jaxb.PlotData;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import sample.scatterplot.persistence.PlotSample;
import sample.scatterplot.persistence.PlotType;

/**
 * <p>REST Web Service. This WS receive the plot type name to draw and the start
 * and end timestamps, queries the database in order to get the list of samples
 * in these dates. With the resulting samples a PlotData is constructed and
 * returned using JSON.</p>
 *
 * <p>All timestamps in string format are milliseconds since the epoch
 * (1/1/1970) prefixed by T (indicating Timestamp).</p>
 *
 * @author ricky
 */
@Path("plot")
@Stateless
public class PlotResource {

    @PersistenceContext
    EntityManager em;

    @Context
    private UriInfo context;

    private SimpleDateFormat format = null;

    /** 
     * Creates a new instance of PlotResource
     */
    public PlotResource() {
        format = new SimpleDateFormat("zyyyyMMddHHmmss");
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    /**
     * All timestamps are generated with a T prefix (JSON rules).
     * @param date The date to print
     * @return The timestamp prefixed by a T
     */
    static public String formatTimestamp(Date date) {
        return "T" + date.getTime();
    }

    /**
     * Main method that returns the list of samples inside a PlotData object.
     * The plot type name is passed as path param and start and end timestamps
     * are passed as query arguments. If start or end timestamps are not passed
     * today is used. Parameters start and end are the milliseconds prefixed
     * by a "T".
     * 
     * @param type The PlotType to plot
     * @param start Start timestamp (can be empty)
     * @param end End timestamp (can be empty)
     * @return a PlotData object with all the samples.
     */
    @GET
    @Produces("application/json")
    @Path("{type}")
    public PlotData getPlotData(
            @PathParam("type") String type,
            @QueryParam("start") String start,
            @QueryParam("end") String end) {
        try {
            System.err.println(type + ": " + start + "-" + end);
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date startDate = null;
            Date endDate = null;
            // get end
            if (end != null) {
                endDate = new Date(Long.parseLong(end.substring(1)));
            } else {
                endDate = cal.getTime();
            }
            // get start
            if (start != null) {
                startDate = new Date(Long.parseLong(start.substring(1)));
            } else {
                cal.add(Calendar.DATE, -1);
                startDate = cal.getTime();
            }
            // get the list of values
            cal.setTime(startDate);

            //System.err.println(type + "-findSamplesBetweenDates");
            //System.err.println("startDate: " + format.format(startDate));
            //System.err.println("endDate: " + format.format(endDate));
            PlotData result = new PlotData(type);
            result.setStart(formatTimestamp(startDate));
            result.setEnd(formatTimestamp(endDate));
            PlotType pt = PlotType.valueOf(type);
            result.setLegend(pt.getLegend());
            result.setDescription(pt.getDescription());
            List<PlotSample> list = em.createNamedQuery(type + "-findSamplesBetweenDates").
                setParameter("begin", startDate).
                setParameter("end", endDate).getResultList();
            if (list != null && !list.isEmpty()) {
                for (PlotSample s: list) {
                    result.getData().put(formatTimestamp(s.getSampleDate()), s.getSampleValue());
                }
            }
            return result;
        } catch (Throwable t) {
            throw new WebApplicationException(t);
        }
    }
}

