package gov.va.med.esr.webservices.jaxws.spring;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

import gov.va.med.esr.delegates.EEDelegate;
import gov.va.med.esr.mvc.controller.PersonFilterType;
import gov.va.med.esr.mvc.model.EDStatusModel;
import gov.va.med.esr.mvc.model.EEModel;
import gov.va.med.esr.mvc.model.EEModelHistory;
import gov.va.med.esr.mvc.model.DeliveryPreferenceModel;

import gov.va.med.esr.mvc.model.RetrieveIVMCandidatesRequest;
import gov.va.med.esr.mvc.model.RetrieveIVMCandidatesResponse;
import gov.va.med.esr.mvc.model.GetIVMLetterStatusesRequest;
import gov.va.med.esr.mvc.model.GetIVMLetterStatusesResponse;
import gov.va.med.esr.mvc.model.UpdateDeliveryPreferenceModel;
import gov.va.med.esr.mvc.model.GetEDStatusRequest;
import gov.va.med.esr.mvc.model.GetEESummaryRequest;
import gov.va.med.esr.mvc.model.GetEESummaryHistoryRequest;
import gov.va.med.esr.mvc.model.GetPersonNotificationRequest;
import gov.va.med.esr.mvc.model.GetDeliveryPreferenceRequest;
import gov.va.med.esr.mvc.model.UpdateDeliveryPreferenceRequest;
import gov.va.med.esr.mvc.model.PersonNotificationModel;
import gov.va.med.esr.mvc.model.UpdateIVMRecordStatusRequest;
import gov.va.med.esr.mvc.model.UpdateIVMRecordStatusResponse;
import gov.va.med.esr.mvc.model.SendIVMUpdatesRequest;
import gov.va.med.esr.mvc.model.SendIVMUpdatesResponse;
import gov.va.med.esr.service.external.EntityFinder;
import gov.va.med.esr.service.external.person.collections.CategoryCollection;
import gov.va.med.esr.service.external.person.CategoryInfo;
import gov.va.med.esr.service.external.person.DeliveryPreferenceInfo;
import gov.va.med.esr.service.external.person.IVMCandidateInfo;
import gov.va.med.esr.service.external.person.IvmLetterCandidateInfo;
import gov.va.med.esr.service.external.person.IVMLastPolledEntityFinder;
import gov.va.med.esr.service.external.person.IVMRecordStatusEntityFinder;
import gov.va.med.esr.service.external.person.IVMSummary;
import gov.va.med.esr.service.external.person.VPIDEntityFinder;
import gov.va.med.esr.webservices.jaxws.spring.interceptor.MessageContextHolder;
import gov.va.med.fw.util.VersionInfo;
import gov.va.med.esr.service.external.person.EntityKeyFactory;
import gov.va.med.esr.service.external.person.AbstractEntityFinder;

import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;

@Endpoint
public class EESummaryEndPoint  {//extends AbstractMarshallingPayloadEndpoint{

	private EEDelegate eeDelegate;

	private VersionInfo versionInfo;

	public EESummaryEndPoint() {
	}

	@PayloadRoot(localPart = "getEESummaryRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected EEModel getEESummary(GetEESummaryRequest eeRequest) throws Exception {
    	//GetEESummaryRequest eeRequest = (GetEESummaryRequest) request;
    	EEModel model = null;

    	String requestName = eeRequest.getRequestName();
    	String userName    = MessageContextHolder.getServiceUser().getUserName();
    	try {
    		model = getEeDelegate().getData(PersonFilterType.convertPersonFilter(eeRequest.getKey(), eeRequest.getIncomeYear(), eeRequest.getKeyType(), userName, requestName));
    		if ( model != null ) {
    			model.setEesVersion(getVersionInfo().getVersion());
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  model;
    }



	@PayloadRoot(localPart = "retrieveIVMCandidatesRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected RetrieveIVMCandidatesResponse retrieveIVMCandidatesRequest(RetrieveIVMCandidatesRequest request) throws Exception {
    	RetrieveIVMCandidatesResponse response = new RetrieveIVMCandidatesResponse();
    	try {
    		IVMSummary summary = getEeDelegate().getIVMCandidatesData(new IVMLastPolledEntityFinder(request.getLastPolledDateTimeStamp()));
    		if ( summary != null ) {
    			List<IVMCandidateInfo> candidates = new ArrayList<IVMCandidateInfo>();
    			for(IVMCandidateInfo candidate: summary.getIVMCandidates().getIVMCandidate()){
    				candidates.add(candidate);
    			}
    			response.setCandidates(candidates);
    			response.setEesVersion(getVersionInfo().getVersion());
    			response.setNumberOfCandidates(summary.getNumberOfIVMCandidates());
    		} else {
    			throw new Exception("No candidates found");
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  response;
    }

	@PayloadRoot(localPart = "getIVMLetterStatusesRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected GetIVMLetterStatusesResponse getIVMLetterStatusesRequest(GetIVMLetterStatusesRequest request) throws Exception {
		GetIVMLetterStatusesResponse response = new GetIVMLetterStatusesResponse();
    	try {
    		IVMSummary summary = getEeDelegate().getIvmLetterCandidatesData();
    		if ( summary != null ) {
    			List<IvmLetterCandidateInfo> letterCandidates = new ArrayList<IvmLetterCandidateInfo>();
    			for (IvmLetterCandidateInfo letterCandidate: summary.getIvmLetterCandidates().getIVMLetterCandidate()){
    				letterCandidates.add(letterCandidate);
    			}
    			response.setIvmLetterCandidates(letterCandidates);
    		} else {
    			throw new Exception("No IVM letter candidates found");
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  response;
    }

	@PayloadRoot(localPart = "updateIVMRecordStatusRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected UpdateIVMRecordStatusResponse updateIVMRecordStatusRequest(UpdateIVMRecordStatusRequest request) throws Exception {
    	UpdateIVMRecordStatusResponse response = new UpdateIVMRecordStatusResponse();
    	try {
    		IVMSummary summary = getEeDelegate().getIVMRecordStatusData(new IVMRecordStatusEntityFinder(request.getTransactionId(), request.getErrorText()));
    		if ( summary != null ) {
    			response.setAcknowledgement(summary.getAcknowledgement());
    			response.setStatus(response.getStatus());
    			response.setEesVersion(getVersionInfo().getVersion());
    		} else {
    			throw new Exception("Unable to update IVM Record status.");
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  response;
    }

	@PayloadRoot(localPart = "sendIVMUpdatesRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected SendIVMUpdatesResponse sendIVMUpdates(SendIVMUpdatesRequest request) throws Exception {
		SendIVMUpdatesResponse response = new SendIVMUpdatesResponse();
		String requestName = "IVMData";
    	String accountName    = MessageContextHolder.getServiceUser().getUserName();
    	request.getSendIVMInfo().setIvmActionCode(request.getIvmActionCode());
    	request.getSendIVMInfo().setBtFinancialInd(request.getBtFinancialInd());

    	try {
    		IVMSummary summary = getEeDelegate().getSendIVMUpdatesData(new VPIDEntityFinder(request.getVpid(), accountName, requestName, request.getIncomeYear(), request.getSendIVMInfo(),
    				request.getIvmLetterInfo()));
    		if (summary != null) {
    			response.setAcknowledgement(summary.getAcknowledgement());
    			response.setStatus(response.getStatus());
    			response.setEesVersion(getVersionInfo().getVersion());
    		} else {
    			throw new Exception("Unable to update IVM Record status.");
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}

    	return  response;
    }


    @PayloadRoot(localPart = "getEESummaryHistoryRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
    protected EEModelHistory getEESummaryHistory(GetEESummaryHistoryRequest eeRequest) throws Exception {
        //GetEESummaryRequest eeRequest = (GetEESummaryRequest) request;
        EEModelHistory model = null;
        String requestName = null;
        if(eeRequest.getRequestName() != null ) requestName = eeRequest.getRequestName();
        String userName    = MessageContextHolder.getServiceUser().getUserName();
        CategoryCollection categories = eeRequest.getCategories();
        CategoryInfo[] catinfo = categories.getCategory();
        for(int i=0; i < catinfo.length; i = i+1){
        	if(catinfo[i].getCategoryName() == null){
        		EEModelHistory modelEr = new EEModelHistory();
        		modelEr.setNoDataMessage("Category Name is Required ");
        		return modelEr;
        	} //WI 324899
        	if(catinfo[i].getCategoryName().trim().equalsIgnoreCase("eligibility") ||
        			catinfo[i].getCategoryName().trim().equalsIgnoreCase("enrollment")||
        			catinfo[i].getCategoryName().trim().equalsIgnoreCase("insurance") ||
        			catinfo[i].getCategoryName().trim().equalsIgnoreCase("disability") ||
        			catinfo[i].getCategoryName().trim().equalsIgnoreCase("aca_mec_start") ||
        			catinfo[i].getCategoryName().trim().equalsIgnoreCase("aca_mec_end") ||
        			catinfo[i].getCategoryName().trim().equalsIgnoreCase("all")) {
        		//continue
        		catinfo[i].setCategoryName(catinfo[i].getCategoryName().trim());

        	}else{
        		EEModelHistory modelError = new EEModelHistory();
        		modelError.setEesVersion(getVersionInfo().getVersion());
        		modelError.setNoDataMessage("Invalid Category Name: " + catinfo[i].getCategoryName());
        		return modelError;
        	}

        	if(catinfo[i].getDateOfService() == null){
        		EEModelHistory modelErr = new EEModelHistory();
        		modelErr.setNoDataMessage("Date of Service is Required ");
        		return modelErr;
        	}
       }

        try {
            model = getEeDelegate().getDataHistory(PersonFilterType.convertPersonFilter(eeRequest.getKey(), eeRequest.getKeyType(), userName, requestName, categories));
            if ( model != null ) {
                model.setEesVersion(getVersionInfo().getVersion());
            }
        }
        catch(Exception e){
            MessageContextHolder.setException(e);
            throw e;
        }
        return  model;
    }

    @PayloadRoot(localPart = "getEligibilityDeterminationRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected EDStatusModel getEDStatus(GetEDStatusRequest eeRequest) throws Exception {
    	EDStatusModel model = null;

    	String userName    = MessageContextHolder.getServiceUser().getUserName();
    	try {
    		model = getEeDelegate().getDataEDStatus(PersonFilterType.convertPersonFilter(eeRequest.getVpid(), null, userName, null));
    		if ( model != null ) {
    			model.setEesVersion(getVersionInfo().getVersion());
    			model.setVpid(eeRequest.getVpid());
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  model;
    }
    @PayloadRoot(localPart = "getPersonNotificationRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected PersonNotificationModel getPersonNotification(GetPersonNotificationRequest eeRequest) throws Exception {
    	PersonNotificationModel model = null;
    	String vpid = null;
    	String survivingVpid = null;
    	String deprecatedVpid = null;
    	String dfn = null;
    	String stationNumber = null;
    	String fromVpid = null;
    	String toVpid = null;
    	String notificationType = null;

    	try {
    		String userName    = MessageContextHolder.getServiceUser().getUserName();
    		if(eeRequest.getNotificationType() != null){
    		 notificationType = eeRequest.getNotificationType();
    		}
    		if( eeRequest.getNotificationType() != null && eeRequest.getPrimaryviewNotification() != null &&
    				eeRequest.getNotificationType().equalsIgnoreCase("PrimaryViewUpdate")
    				&& eeRequest.getPrimaryviewNotification().getVPID() != null){
    			 vpid = eeRequest.getPrimaryviewNotification().getVPID();

    			 model = getEeDelegate().getDataPersonNotificationStatus(PersonFilterType.convertPersonFilter(vpid, null, userName, notificationType,
    	    				survivingVpid,deprecatedVpid,dfn,stationNumber,fromVpid,toVpid));
    		}

    		if(eeRequest.getLinkNotification() != null && eeRequest.getNotificationType() != null &&
    				eeRequest.getNotificationType().equalsIgnoreCase("Link")){
    			survivingVpid = eeRequest.getLinkNotification().getSurvivingVPID();
    			deprecatedVpid = eeRequest.getLinkNotification().getDepricatedVPID();
    			model = getEeDelegate().getDataPersonNotificationStatus(PersonFilterType.convertPersonFilter(vpid, null, userName, notificationType,
	    				survivingVpid,deprecatedVpid,dfn,stationNumber,fromVpid,toVpid));
    		}

    		if(eeRequest.getMoveNotification() != null && eeRequest.getNotificationType() != null &&
    				eeRequest.getNotificationType().equalsIgnoreCase("Move")){
    			dfn = eeRequest.getMoveNotification().getDFN();
    			stationNumber = eeRequest.getMoveNotification().getStationNumber();
    			fromVpid = eeRequest.getMoveNotification().getFromVPID();
    			toVpid = eeRequest.getMoveNotification().getFromVPID();
    			model = getEeDelegate().getDataPersonNotificationStatus(PersonFilterType.convertPersonFilter(vpid, null, userName, notificationType,
	    				survivingVpid,deprecatedVpid,dfn,stationNumber,fromVpid,toVpid));
    		}

    		 if(model != null){

    				 model.setAcknowledgement("Person Notification Received");
    				 model.setEesVersion(getVersionInfo().getVersion());
    				 model.setPnstatus(null);
    		 }
    		 else{
    			 model = new PersonNotificationModel();
    			 if(eeRequest.getNotificationType() != null){
    	    			if(!eeRequest.getNotificationType().equalsIgnoreCase("PrimaryViewUpdate") ||
    	    					!eeRequest.getNotificationType().equalsIgnoreCase("Move") ||
    	    					!eeRequest.getNotificationType().equalsIgnoreCase("Link")){
    	    				model.setNoDataMessage("Invalid Notification Type :" + eeRequest.getNotificationType());
    	    			}else{
    	    				model.setNoDataMessage("Missing Required Fields");
    	    			}
    			 }
    			 else{
    				 model.setNoDataMessage("Notification Type is Required");
    			 }
    			 model.setEesVersion(getVersionInfo().getVersion());
    		 }
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  model;
    }

    @PayloadRoot(localPart = "getDeliveryPreferenceRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected DeliveryPreferenceModel getDeliveryPreference(GetDeliveryPreferenceRequest eeRequest) throws Exception {
    	//GetEESummaryRequest eeRequest = (GetEESummaryRequest) request;
    	DeliveryPreferenceModel model = null;

    	String userName    = MessageContextHolder.getServiceUser().getUserName();
    	if( eeRequest.getKeyType()== null  ||  !eeRequest.getKeyType().equalsIgnoreCase("VPID") || eeRequest.getKey() == null){
    		model = new DeliveryPreferenceModel();
    		model.setStatus("Delivery Preference: Invalid/Missing Data  " );
    		model.setEesVersion(getVersionInfo().getVersion());
    		return model;
    	}
    	try {
    		model = getEeDelegate().getDataDeliveryPreference(PersonFilterType.convertPersonFilter(eeRequest.getKey(), eeRequest.getKeyType(), userName,null));
    		if ( model != null ) {
    			model.setEesVersion(getVersionInfo().getVersion());
    		} else{
    			model = new DeliveryPreferenceModel();
    			model.setEesVersion(getVersionInfo().getVersion());
    		}

    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  model;
    }
    @PayloadRoot(localPart = "updateDeliveryPreferenceRequest", namespace = "http://jaxws.webservices.esr.med.DNS   /schemas")
	protected UpdateDeliveryPreferenceModel updateDeliveryPreference(UpdateDeliveryPreferenceRequest eeRequest) throws Exception {
    	//GetEESummaryRequest eeRequest = (GetEESummaryRequest) request;
    	UpdateDeliveryPreferenceModel model = null;
    	DeliveryPreferenceInfo deliveryPreferenceInfo = null;
    	if( eeRequest.getKeyType()== null  ||  !eeRequest.getKeyType().equalsIgnoreCase("VPID") || eeRequest.getKey() == null){
    		model = new UpdateDeliveryPreferenceModel();
    		model.setStatus("Update Delivery Preference: Invalid/Missing Data  "  );
    		model.setEesVersion(getVersionInfo().getVersion());
    		return model;
    	}
    	if(eeRequest.getDeliveryPreferenceInfo() != null && eeRequest.getDeliveryPreferenceInfo().getDeliveryPreference() != null &&
    			(eeRequest.getDeliveryPreferenceInfo().getDeliveryPreference().equalsIgnoreCase("MAIL") ||
    			 eeRequest.getDeliveryPreferenceInfo().getDeliveryPreference().equalsIgnoreCase("ONLINE")) ){
    	    deliveryPreferenceInfo= eeRequest.getDeliveryPreferenceInfo();
    	}
    	else{
    		model = new UpdateDeliveryPreferenceModel();
    		model.setStatus("Update Delivery Preference: Invalid Data");
    		model.setEesVersion(getVersionInfo().getVersion());
    		return model;
    	}
    	if(eeRequest.getDeliveryPreferenceInfo() != null  && eeRequest.getDeliveryPreferenceInfo().getDeliveryPreference() != null){
    		if(eeRequest.getDeliveryPreferenceInfo().getDeliveryPreference().equalsIgnoreCase("MAIL")){

    				 	if(eeRequest.getDeliveryPreferenceInfo().getEmailAddress() != null || eeRequest.getDeliveryPreferenceInfo().getEmailType() != null){
    				 		model = new UpdateDeliveryPreferenceModel();
    				 		model.setStatus("Update Delivery Preference: Email/Email Type is not a required field for the option MAIL ");
    				 		model.setEesVersion(getVersionInfo().getVersion());
    				 		return model;
    				 	}

    		} else {
    			if(eeRequest.getDeliveryPreferenceInfo().getDeliveryPreference().equalsIgnoreCase("ONLINE")){
    				if(eeRequest.getDeliveryPreferenceInfo().getEmailAddress() == null ||
    						eeRequest.getDeliveryPreferenceInfo().getEmailType() == null ){
    						model = new UpdateDeliveryPreferenceModel();
    						model.setStatus("Update Delivery Preference: Missing Data : Email/Email Type");
    						model.setEesVersion(getVersionInfo().getVersion());
    						return model;
    					}
    				if(eeRequest.getDeliveryPreferenceInfo().getEmailType() != null  &&
    						(eeRequest.getDeliveryPreferenceInfo().getEmailType().equalsIgnoreCase("PRIVATE") ||
    		    			 eeRequest.getDeliveryPreferenceInfo().getEmailType().equalsIgnoreCase("BUSINESS"))){
    						    //
    					}else {
    						model = new UpdateDeliveryPreferenceModel();
    						model.setStatus("Update Delivery Preference: Invalid Data     " + eeRequest.getDeliveryPreferenceInfo().getEmailType());
    						model.setEesVersion(getVersionInfo().getVersion());
    						return model;
    					}
    			}
    		}
    	}
    	String userName    = MessageContextHolder.getServiceUser().getUserName();
    	try {
    		model = getEeDelegate().getDataUpdateDeliveryPreference(PersonFilterType.convertPersonFilter(eeRequest.getKey(), eeRequest.getKeyType(), userName, null,deliveryPreferenceInfo));
    		if ( model != null  && model.getUpdateDeliveryPreference() != null) {
    			model.setEesVersion(getVersionInfo().getVersion());
    			model.setAcknowledgement("Request Received and Delivery Preference is updated");
    		    model.setUpdateDeliveryPreference(null);
    		}
    		else{
    			model.setEesVersion(getVersionInfo().getVersion());
    			model.setAcknowledgement("Request Received and Delivery Preference is not updated. The data field is read only.");
    		    model.setUpdateDeliveryPreference(null);
    		}
    	}
    	catch(Exception e){
    		MessageContextHolder.setException(e);
    		throw e;
    	}
    	return  model;
    }

	public EEDelegate getEeDelegate() {
		return eeDelegate;
	}

	public void setEeDelegate(EEDelegate eeDelegate) {
		this.eeDelegate = eeDelegate;
	}

	public VersionInfo getVersionInfo() {
		return versionInfo;
	}

	public void setVersionInfo(VersionInfo versionInfo) {
		this.versionInfo = versionInfo;
	}
}
