package com.k_int.ciim.ui.system;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.k_int.ciim.base.dto.DataExtractDTO;
import com.k_int.ciim.core.management.ManagementServiceImpl;
import com.k_int.ciim.ref.GranularityEnum;

@Path("/system/extract")
@Produces("text/html")
public class ExtractManager 
{
	private ManagementServiceImpl mgmt_service = null;
	
	//app context setter
	public void setMgmtService(ManagementServiceImpl mgmtService) 
	{
		mgmt_service = mgmtService;
	}
	
	public ExtractManager(){;}
	
	@GET
	@Produces("application/json")
	public DataExtractDTO getExtractDetails()
	{
		return mgmt_service.getCurrentExtractInfo();
	}
	
	@POST
	@Produces({MediaType.TEXT_PLAIN})
	public String extract()
	{
	
		//return mgmt_service.runExtract(false, null);
		return "This task is not currently implemented";
	}
	
	@POST
	@Consumes("application/x-www-form-urlencoded")
	@Produces({MediaType.TEXT_PLAIN})
	public String actions(@QueryParam("action") String action, MultivaluedMap<String, String> form_params)
	{
		String retval = "Failed to update extract settings";
		
		try
		{
			if(action != null && action.equalsIgnoreCase("update"))
			{
				
				DataExtractDTO extract_dto = mgmt_service.getCurrentExtractInfo();
				
				if(form_params.getFirst("nextDue") != null && form_params.getFirst("nextDue").trim().length() > 0)
				{
					SimpleDateFormat sdfSource = new SimpleDateFormat("dd/MM/yy hh:mm");
					
					Date date = sdfSource.parse(form_params.getFirst("nextDue"));
					
					extract_dto.setNextDue(date);
				}
				if(form_params.getFirst("frequency") != null && form_params.getFirst("frequency").trim().length() > 0)
				{
					extract_dto.setRerunFrequencyInMinutes(new Integer(form_params.getFirst("frequency")));
				}
				if(form_params.getFirst("interval") != null && form_params.getFirst("interval").trim().length() > 0)
				{
					extract_dto.setMaxExtractInterval(new Integer(form_params.getFirst("interval")));
					
					//only update granularity if we have a value for it
					if(form_params.getFirst("granularity") != null && form_params.getFirst("granularity").trim().length() > 0)
					{
						GranularityEnum granularity =  GranularityEnum.valueOf(form_params.getFirst("granularity").toUpperCase());
						extract_dto.setMaxExtractIntervalGranularity(granularity);
					}
				}
				
				mgmt_service.updateCurrentExtractionInfo(extract_dto);

				retval = "Successfully updated Extract Settings";
			}
		}
		catch(ParseException pe)
		{
			//log.error(pe);
		}
		
		return retval;
	}
}
