package gov.va.med.esr.ui.admin.action;
 
import gov.va.med.esr.common.model.comms.HandBookBatchRequest;
import gov.va.med.esr.common.model.comms.HandbookBatchRequestStatistics;
import gov.va.med.esr.common.model.lookup.HandBookRequestStatusType;
import gov.va.med.esr.common.util.CommonDateUtils;
import gov.va.med.esr.service.SystemParameterService;
import gov.va.med.esr.ui.ApplicationConstants;
import gov.va.med.esr.ui.ApplicationConstants.MessageKeys;
import gov.va.med.esr.ui.common.action.AbstractAction;
import gov.va.med.esr.ui.common.util.DateUtils;
import gov.va.med.fw.model.EntityKey;
import gov.va.med.fw.model.EntityKeyFactory;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.util.StringUtils;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class HandBookBatchRequestAction extends AbstractAction {
	
	public static final String FORWARD_DISPLAY_LIST_SUCCESS = "listsuccess";

	public static final String REQUEST_ADDED = "message.handBookBatchRequestAdded";
	public static final String REQUEST_CANCELED = "message.handBookBatchRequestCanceled";

	public static final String FORWARD_DISPLAY_EDIT = "displayEdit";

	public static final String FORWARD_DISPLAY_NEW = "displayNewHandBookBatch";
	
	public static final String FORWARD_DISPLAY_STATISTICS = "displayStatistics";
	
	public static final String FORWARD_HANDBOOK_FILE_STATISTICS = "displayHandbookFileStatistics";

	public static final String REQUIRED = MessageKeys.ERRORS_REQUIRED;

	public static final String LABEL_KEY_RELEASE_DATE="Release Date";
	
	public static final String LABEL_KEY_PRIORITY_GRPOUP="Priority Group or Preferred Facilities";
	
	public static final String LABEL_KEY_FACILITIES="Parent Facilities";
	
	public static final String LABEL_KEY_RELEASE_CONTROL="Release Control#";
	
	public static final String LABEL_KEY_MAX_REC_COUNT="Maximum Records";
	
	public static final String LABEL_BATCH_NOTE="Batch Note";
	
	public static final String ERROR_MAX_REC_COUNT="errors.MaxRecCount";
	
	public static final String ERROR_NOTE_SIZE="errors.RemarkSize";
	
	public static final String ERROR_DATE_NEED_EQ_GT_SYSTEMDATE = "errors.validateNeedToEqOrGtSystemDate";
	
	public static final String ERROR_FACILITIES="error.facilites";

	public static final String PARAM_RELEASE_DATE="releaseDate";
	
    public SystemParameterService systemParameterService=null;

	public SystemParameterService getSystemParameterService() {
		return systemParameterService;
	}

	public void setSystemParameterService(
			SystemParameterService systemParameterService) {
		this.systemParameterService = systemParameterService;
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

			List handBookBatchRequests = getHandBookService().getHandBookBatchRequests();
			if (handBookBatchRequests != null && !handBookBatchRequests.isEmpty())
				request.setAttribute("handBookBatchRequests", handBookBatchRequests);

			return mapping.findForward(FORWARD_DISPLAY_LIST_SUCCESS);
	}

	public ActionForward cancelBatchRequest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
       try{
		HandBookBatchRequestForm handBookBatchRequestForm = (HandBookBatchRequestForm) form;
		String batchRequestId = handBookBatchRequestForm.getBatchRequestId();
		EntityKey key = EntityKeyFactory.createEntityKey(batchRequestId,
				HandBookBatchRequest.class);
		HandBookBatchRequest handBookBatchRequest = this.getHandBookService().getHandbookBatchRequestEntry(key);
	
 		 HandBookRequestStatusType statusType=this.getLookupService().getHandBookRequestStatusTypeByCode(HandBookRequestStatusType.CANCELLED.getCode());
		Date batchCancelDate= DateUtils.getCurrentDate();
		 handBookBatchRequest.setBatchCancelDate(batchCancelDate);
		this.getHandBookService().updateHandBookBatchRequestStatus(handBookBatchRequest,statusType);
		 addInformationMessage(request, REQUEST_CANCELED);
		
       }catch (Exception dex) {
			logger.error(
					"ERROR in cancleing handbook batch request " ,dex);
			 addInformationMessage(request, "Error cancel Batch Request");
			
			return list(mapping, form, request, response);
       }
      
	            return list(mapping, form, request, response);
	    }
		
	public ActionForward saveBatchRequest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		boolean isFormValid = validateForm(mapping, form, request, response);
		if(!isFormValid){
			return mapping.findForward(FORWARD_DISPLAY_NEW);
		}
       try{
		HandBookBatchRequestForm handBookBatchRequestForm = (HandBookBatchRequestForm) form;
		HandBookBatchRequest handBookBatchRequest = new HandBookBatchRequest();
		
		
		
	            this.getConversionService().convert(handBookBatchRequestForm,handBookBatchRequest);
	            this.getHandBookService().addHandBookBatchRequest(handBookBatchRequest);
	            /*
	             * int estCount=this.getHandBookService().getEstRecordCountForBatch(handBookBatchRequest.getEntityKey().getKeyValueAsString());
	            if(estCount >0){
	            handBookBatchRequest.setBatchReleaseSize(String.valueOf(estCount));
	            this.getHandBookService().getHandbookBatchRequestDAO().saveObject(handBookBatchRequest);
	            }
	            */
	            if(handBookBatchRequestForm.isUpdateReleaseCtl()){
	            	this.systemParameterService.updateDefaultHandBookReleaseCtl(handBookBatchRequestForm.getReleaseCtl());
	            }
	            addInformationMessage(request, REQUEST_ADDED);
	           // return list(mapping, form, request, response);
	           // return mapping.findForward(FORWARD_DISPLAY_NEW);
	            return displayNew(mapping, form, request, response);
		        
	    		
       }catch (Exception dex) {
			logger.error(
					"ERROR to insert a new handbookbatch request entry " ,dex);
			addActionMessage(request, "Error Adding Batch Request"+dex.getMessage());
			
			return mapping.findForward(FORWARD_DISPLAY_NEW);
			
       }
      
	           
	    }
		

	
	private boolean validateForm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HandBookBatchRequestForm handBookBatchRequestForm = (HandBookBatchRequestForm) form;

		boolean valid = true;
		if (handBookBatchRequestForm.getReleaseDate() == null	 || StringUtils.isEmpty(handBookBatchRequestForm.getReleaseDate())		) {
			addActionMessage(request, REQUIRED, LABEL_KEY_RELEASE_DATE);
			valid = false;
		}
		else if (StringUtils.isNotEmpty(handBookBatchRequestForm.getReleaseDate())){
	    //				 Validate dates
		        Date releaseDate = null;
	            try
	            {
	            	releaseDate = DateUtils.getDate(handBookBatchRequestForm.getReleaseDate());
	            	 Date currentDate = DateUtils.getCurrentDate();
	            	 if (releaseDate!=null && releaseDate.compareTo(currentDate) < 0) {
	     	            
	                     addActionMessage(request, ERROR_DATE_NEED_EQ_GT_SYSTEMDATE, LABEL_KEY_RELEASE_DATE);
	                     valid = false;
	                 }
	            }
	            catch (Exception e)
	            {
	            	addActionMessage(request, ApplicationConstants.MessageKeys.ERRORS_DATE, LABEL_KEY_RELEASE_DATE);
	            	valid = false;
	            }
	        }
		
		
		if (handBookBatchRequestForm.getPriorityGroup() == null
				&& (handBookBatchRequestForm.getVisnVamc()== null || handBookBatchRequestForm.getVisnVamc().length==0)) {
			valid = false;
			//addActionMessage(request, REQUIRED, ERROR_FACILITIES);
			addActionMessage(request, REQUIRED, LABEL_KEY_PRIORITY_GRPOUP);
		}
		if (handBookBatchRequestForm.getReleaseCtl() == null ) {
			valid = false;
			addActionMessage(request, REQUIRED, LABEL_KEY_RELEASE_CONTROL);
		}
		if (handBookBatchRequestForm.getMaxRecord() >1000000 ||handBookBatchRequestForm.getMaxRecord() <1) {
			valid = false;
			addActionMessage(request, ERROR_MAX_REC_COUNT, LABEL_KEY_MAX_REC_COUNT);
		}	
		if (handBookBatchRequestForm.getReleaseNote().length()>240) {
			valid = false;
			addActionMessage(request, ERROR_NOTE_SIZE, LABEL_BATCH_NOTE);
		}
		return valid;
	}

	public ActionForward displayNew(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HandBookBatchRequestForm handBookBatchRequestForm = (HandBookBatchRequestForm) form;
           this.populateFormData(handBookBatchRequestForm);
       return mapping.findForward(FORWARD_DISPLAY_NEW);
	}
	
	public ActionForward displayStatistics(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
	  String releaseDateStr = request.getParameter(PARAM_RELEASE_DATE);
      Date releaseDate = DateFormat.getDateInstance(DateFormat.SHORT).parse(releaseDateStr);
      
      List<HandbookBatchRequestStatistics> handBookBatchRequests = getHandBookService().getHandbookBatchRequestStatistics(releaseDate);
      if (handBookBatchRequests != null && !handBookBatchRequests.isEmpty())
		request.setAttribute("handBookBatchRequestStats", handBookBatchRequests);
	
      return mapping.findForward(FORWARD_DISPLAY_STATISTICS);
	}
	
	public ActionForward reset(ActionMapping mapping, ActionForm form,
	            HttpServletRequest request, HttpServletResponse response) throws Exception {
		       	return displayNew(mapping, form, request, response);
	    }
	 private void populateFormData(HandBookBatchRequestForm handBookBatchRequestForm){
		 handBookBatchRequestForm.initialize();
		 try{
			 String releseCtl=this.systemParameterService.getHandBookReleaseCtl();
			 handBookBatchRequestForm.setReleaseCtl(releseCtl);
			 handBookBatchRequestForm.setReleaseDate("");
			 handBookBatchRequestForm.setDefaultReleaseCtl(releseCtl);
			 handBookBatchRequestForm.setMaxRecord(1000);
			 handBookBatchRequestForm.setReleaseNote("");
			 handBookBatchRequestForm.setUpdateReleaseCtl(false);
			 handBookBatchRequestForm.setPriorityGroup("all");
		 }catch(ServiceException ex) {
	            logger.error("Error in getting default " +
	            		"HANDBOOK_BATCH_RELEASE_CONTROL_NUMBER from APP_PARAMETER table",ex.getCause());
	        }
	 }
	public void afterPropertiesSet() throws Exception {

	}
	
	/**
	 * Initialize and get the Struts lookup dispatch method map hashmap.
	 * 
	 * @return the method map
	 * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
	 */
	protected Map getKeyMethodMap() {
		Map map = new HashMap();
		map.put("button.handBookBatchRequest.add", "saveBatchRequest");
		map.put("button.handBookBatchRequest.cancel", "list");
		map.put("button.handBookBatchRequest.list", "list");
		map.put("button.handBookBatchRequest.reset", "reset");
		map.put("button.handBookBatchRequest.displayNew", "displayNew");
		map.put("button.handBookBatchRequest.cancelBatch", "cancelBatchRequest");	
		map.put("link.handBookBatchRequest.displayStatistics", "displayStatistics");
		
		return map;
	}

}
