/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TestRest.service;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import TestRest.Assocamo;
import com.sun.jersey.api.core.ResourceContext;
import TestRest.converter.AmplitudesConverter;
/**
 *
 * @author aparnab
 */
@Path("/amplitudes/query/")
public class QueryAmplitudeResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;

    public QueryAmplitudeResource(){
    }

    @GET
    @Produces({"application/xml", "application/json"})
    public AmplitudesConverter get(
    @QueryParam("ampid")    @DefaultValue("-1")    int ampid,
    @QueryParam("query")    @DefaultValue("") String query) {

        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            if(ampid != -1){
                return new AmplitudesConverter(getEntities(ampid, query), uriInfo.getAbsolutePath());
            } else {
                return new AmplitudesConverter();
            }
            } finally {
            persistenceSvc.commitTx();
            persistenceSvc.close();
            }
    }
    //events for an ampid
    protected Assocamo getEntities(int ampid, String query) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        Assocamo amp = new Assocamo();
        Query a = em.createNamedQuery("Assocamo.findByAmpid").setParameter("ampid",ampid);
        amp = (Assocamo)a.getSingleResult();
        System.out.println("number of amplitudes =" + a.getResultList().size());
        return amp;
    }
}
