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

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

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
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.DateUtil;
import cz.hsrs.rest.ParamsList;
import cz.hsrs.rest.beans.ExceptionBean;
import cz.hsrs.rest.util.TrackRestUtil;

/**
 * @author mkepka
 *
 */
@Path("/track/")
public class TrackRest {

	public static Logger logger = Logger.getLogger("TrackRest");
	
    /**
     * Empty constructor
     */
	public TrackRest() {
		super();
	}
    
	/**
	 * /rest/track/dates?group_name=
	 * /rest/track/dates?group_id=
	 * /rest/track/dates?unit_id=
	 * 
	 * @param unitIds
	 * @param groupId
	 * @param req
	 * @return
	 */
	@Path("/dates")
    @GET
	public Response getDatesOfTracks(
			@QueryParam(ParamsList.UNIT_ID) String unitIds,
			@QueryParam(ParamsList.GROUP_ID) Integer groupId,
			@QueryParam(ParamsList.GROUP_NAME) String groupName,
			@Context HttpServletRequest req){
		try {
			//LoginUser loggedUser = AuthUtil.getAuthenticatedLoginUser(req);
			if(groupId == null) {
				//groupId = UserUtil.getUserGroupId(loggedUser.getUserName());
			}
			String jsonTimes;
			if(unitIds!= null && !unitIds.isEmpty()){
				jsonTimes = TrackRestUtil.getDatesByUnits(unitIds);
			}
    		else if (groupId != null){
    			jsonTimes = TrackRestUtil.getDatesByUnitsByGroup(groupId);
    			
    		}
    		else if(groupName !=null && !groupName.isEmpty()) {
    			jsonTimes = TrackRestUtil.getDatesByUnitsByGroup(groupName);
    		}
    		else {
    			throw new SQLException("Wrong combination of parameters");
    		}
            return Response.ok()
                    .entity(jsonTimes)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                    .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();
		}*/
	}
	
	/**
	 * /rest/track/points
	 * /rest/track/points?unit_id=352625691996753&from_time=2022-03-19 10:00:00&to_time=2022-03-29 12:00:00
	 * @param unitId
	 * @param fromTime
	 * @param toTime
	 * @param req
	 * @return
	 */
	@Path("/points")
    @GET
	public Response getPointsOfTrack(
			@QueryParam(ParamsList.UNIT_ID) Long unitId,
			@QueryParam(ParamsList.SENSOR_ID) String sensorIds,
			@QueryParam(ParamsList.FROM_TIME) String fromTime,
			@QueryParam(ParamsList.TO_TIME) String toTime,
			@Context HttpServletRequest req){
		try {
			//LoginUser loggedUser = AuthUtil.getAuthenticatedLoginUser(req);

			if(fromTime != null && toTime != null) {
				long weekInMilis = (7*24*60*60*1000);
				if((DateUtil.parseTimestamp(toTime).getTime() - DateUtil.parseTimestamp(fromTime).getTime()) <= weekInMilis) {
					String geoJson = TrackRestUtil.getTrackPoints(unitId, sensorIds, fromTime, toTime);
					return Response.ok()
		                .entity(geoJson)
		                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
		                .build();
				}
				else {
					throw new SQLException("Too long interval for data selection");
				}
				
			}
			else if(fromTime != null && toTime == null){
				String geoJson = TrackRestUtil.getTrackPoints(unitId, sensorIds, fromTime, toTime);
				return Response.ok()
	                .entity(geoJson)
	                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
	                .build();
			}
			else {
				throw new SQLException("Wrong combination of parameters");
			}
		} catch (SQLException e) {
			return Response.status(HttpStatus.ORDINAL_500_Internal_Server_Error)
                .entity(new ExceptionBean(e.getClass().getName(), e.getLocalizedMessage()))
                .build();
		} catch (ParseException e) {
			return Response.status(HttpStatus.ORDINAL_400_Bad_Request)
	                .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();
		}*/
	}
}