/**
 * 
 */
package cz.hsrs.rest.provider;

import java.sql.SQLException;
import java.util.logging.Logger;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.mortbay.jetty.HttpStatus;

import cz.hsrs.db.util.ExportUtil;
import cz.hsrs.db.util.UserUtil;
import cz.hsrs.rest.ParamsList;
import cz.hsrs.rest.beans.ExceptionBean;
import cz.hsrs.rest.util.AuthUtil;
import cz.hsrs.servlet.security.LoginUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author mkepka
 *
 */
@Path("/observation/")
public class ObservationRest {
    
    public static Logger logger = Logger.getLogger("ObservationRest");

    /**
     * Empty constructor
     */
    public ObservationRest() {
        super();
    }
    
    /**
     * Method provides 
     * @return
     * /rest/observation/export?group_id=25&sensor_id=340340092&from_time=2021-05-30&to_time=2021-05-31&style=crosstab
     * /rest/observation/export?group_id=25&sensor_id=340340092&from_time=2021-05-30&to_time=2021-05-30+04:00:00&style=crosstab&nullable=false
     * /rest/observation/export?unit_id=1305167563044155,1305167563032199,1305167563051210&sensor_id=340340092&from_time=2021-05-30&to_time=2021-05-30+04:00:00&style=crosstab&nullable=false
     */
    @Path("/export")
    @GET
    public Response getObservationsCrossTab(
            @QueryParam(ParamsList.SENSOR_ID) Long sensorId,
            @QueryParam(ParamsList.UNIT_ID) String unitIds,
            @QueryParam(ParamsList.GROUP_ID) Integer groupId,
            @QueryParam(ParamsList.FROM_TIME) String fromTime,
            @QueryParam(ParamsList.TO_TIME) String toTime,
            @QueryParam(ParamsList.EXPORT_STYLE) String exportStyle,
            @DefaultValue("true") @QueryParam("nullable") Boolean nullable,
            @Context HttpServletRequest req){
        try {
            LoginUser loggedUser = AuthUtil.getAuthenticatedLoginUser(req);
            if(exportStyle.equalsIgnoreCase(ParamsList.CROSS_TAB_STYLE)) {
                if(groupId == null) {
                	groupId = UserUtil.getUserGroupId(loggedUser.getUserName());
                }
                String CSV;
                if(unitIds!= null && !unitIds.isEmpty()){
                	CSV = ExportUtil.getObservationsBySensorByUnitsCross(sensorId, unitIds, groupId, fromTime, toTime, nullable);
                }
                else {
                	CSV = ExportUtil.getObservationsBySensorByGroupCross(sensorId, groupId, fromTime, toTime, nullable);
                }           
                return Response.ok()
                        .entity(CSV)
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
                        .build();
            } else {
                return Response.ok()
                        .entity("Empty")
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)
                        .build();
            }
            
        } catch (SQLException e) {
            return Response.status(HttpStatus.ORDINAL_500_Internal_Server_Error)
                    .entity(new ExceptionBean(e.getClass().getName(), e.getLocalizedMessage()))
                    .build();
        } catch (AuthenticationException e) {
        	return Response.status(HttpStatus.ORDINAL_401_Unauthorized)
                    .entity(new ExceptionBean(e.getClass().getName(), e.getLocalizedMessage()))
                    .build();
		}
    }
    
    @Path("/exportstyle")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getExportStyles() {
    	JSONArray arr = new JSONArray();
    	/* crosstab style*/
    	JSONObject obj1 = new JSONObject();
    	obj1.put("style_id", "crosstab");
    	obj1.put("style_name", "Cross table");
    	obj1.put("description", "Table with dates in rows and units/sensors in columns.");
    	arr.add(obj1);
    	
    	/* timeseries style*/
    	JSONObject obj2 = new JSONObject();
    	obj2.put("style_id", "timeseries");
    	obj2.put("style_name", "Time series table");
    	obj2.put("description", "Table with units in rows and dates in columns, available for one observed property.");
    	arr.add(obj2);
    	
        return Response.ok()
                .entity(arr)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .build();
    }
}