package gov.va.med.esr.service.external;

import gov.va.med.esr.common.model.comms.DeliveryPreference;
import gov.va.med.esr.common.model.comms.DeliveryPreferenceEmail;
import gov.va.med.esr.common.model.comms.Document;
import gov.va.med.esr.common.model.comms.DocumentReceipt;
import gov.va.med.esr.common.model.comms.HealthBenefitPlan;
import gov.va.med.esr.common.model.lookup.DocumentType;
import gov.va.med.esr.common.model.lookup.EmailType;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.service.HandBookService;
import gov.va.med.esr.service.PersonHelperService;
import gov.va.med.esr.service.external.person.DeliveryPreferenceInfo;
import gov.va.med.esr.service.external.person.EESummary;
import gov.va.med.fw.persistent.DAOException;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ExternalHandBookFactoryImpl extends AbstractComponent implements ExternalHandBookFactory {

	
	private PersonHelperService personHelperService = null;
	
	private HandBookService handBookService = null;
	

	public HandBookService getHandBookService() {		
		return handBookService;
	}

	public void setHandBookService(HandBookService handBookService) {
		this.handBookService = handBookService;
	}

	public PersonHelperService getPersonHelperService() {
		return personHelperService;
	}

	public void setPersonHelperService(PersonHelperService personHelperService) {
		this.personHelperService = personHelperService;
	}

	public List buildHandBookInfo(Person person, HandBookRequestInfo hbReqInfo) throws ServiceException, DAOException {
		if (person == null || hbReqInfo == null)
			return null;		
		List handBookList = new ArrayList();
		String vpid = person.getIdentityTraits().getVpid().getVPID();		
		List results = getHandBookService().getHandbookInformation(vpid);
		if(results != null && !results.isEmpty()){
			if(hbReqInfo.getVersion().equalsIgnoreCase("ALL")){
				buildAllHBVersion(results,hbReqInfo,handBookList);				
			}
			else{
				buildCurrentHBVersion(results,hbReqInfo,handBookList);				
			}
			
		}
		return handBookList;
	}
	
	private List buildAllHBVersion(List results, HandBookRequestInfo hbReqInfo,List handBookList){
		
		for (Iterator iter = results.iterator(); iter.hasNext();) {
			DocumentReceipt docReceipt = (DocumentReceipt) iter
			.next();
			buildDocument(docReceipt,hbReqInfo,handBookList );
			
			
		}
		return handBookList;
		
	}
	
	private List buildCurrentHBVersion(List results, HandBookRequestInfo hbReqInfo,List handBookList){
		
		DocumentReceipt docReceipt = (DocumentReceipt) results.get(0);
		buildDocument(docReceipt,hbReqInfo,handBookList );
		return handBookList;
		
	}
	
	private List buildDocument(DocumentReceipt docReceipt,HandBookRequestInfo hbReqInfo, List handBookList){
		if(hbReqInfo.getDocType().equalsIgnoreCase("ALL")){
			Set Documents = docReceipt.getDocuments();
			for (Iterator iter = Documents.iterator(); iter.hasNext();) {
				Document doc = (Document) iter
				.next();
				HandBookInfo hbi = new HandBookInfo();
				hbi.setDocType(doc.getDocumentType().getName());
				hbi.setGeneratedDate(doc.getCreationDate());
				hbi.setName(doc.getFileInfo().getName());
				hbi.setPhysicalLocation(doc.getFileInfo().getDirectory().getMountPoint().getName() + doc.getFileInfo().getDirectory().getName());
				hbi.setReleaseControlNumber(docReceipt.getReleaseControlNumber());
				hbi.setVersion(docReceipt.getVersionNumber());
				handBookList.add(hbi);
			}
			
		}
		else if(hbReqInfo.getDocType().equalsIgnoreCase("HANDBOOK")){
			Set Documents = docReceipt.getDocuments();
			for (Iterator iter = Documents.iterator(); iter.hasNext();) {
				Document doc = (Document) iter.next();
				if(DocumentType.isHandBook(doc.getDocumentType())){
					HandBookInfo hbi = new HandBookInfo();
					hbi.setDocType(doc.getDocumentType().getName());
					hbi.setGeneratedDate(doc.getCreationDate());
					hbi.setName(doc.getFileInfo().getName());
					hbi.setPhysicalLocation(doc.getFileInfo().getDirectory().getMountPoint().getName() + doc.getFileInfo().getDirectory().getName());
					hbi.setReleaseControlNumber(docReceipt.getReleaseControlNumber());
					hbi.setVersion(docReceipt.getVersionNumber());
					handBookList.add(hbi);					
				}			
			}
			
		}
		else{
			Set Documents = docReceipt.getDocuments();
			for (Iterator iter = Documents.iterator(); iter.hasNext();) {
				Document doc = (Document) iter
				.next();
				if(DocumentType.isBenefitsProfile(doc.getDocumentType())){
					HandBookInfo hbi = new HandBookInfo();
					hbi.setDocType(doc.getDocumentType().getName());
					hbi.setGeneratedDate(doc.getCreationDate());
					hbi.setName(doc.getFileInfo().getName());
					hbi.setPhysicalLocation(doc.getFileInfo().getDirectory().getMountPoint().getName() + doc.getFileInfo().getDirectory().getName());
					hbi.setReleaseControlNumber(docReceipt.getReleaseControlNumber());
					hbi.setVersion(docReceipt.getVersionNumber());
					handBookList.add(hbi);	
				}			
			}
			
		}
		
		return handBookList;
		
	}
	
	public List buildHBDataString(Person person, HandBookRequestInfo hbReqInfo) throws ServiceException, DAOException {
		if (person == null || hbReqInfo == null)
			return null;		
		List handBookList = new ArrayList();
		String vpid = person.getIdentityTraits().getVpid().getVPID();		
		
		List results = getHandBookService().getHandbookInformation(vpid);
		
		if(results != null && !results.isEmpty()){			
			if(hbReqInfo.getVersion().equalsIgnoreCase("ALL")){
				buildAllDataStringVersion(results,hbReqInfo,handBookList);			
			}
			else{				
				buildCurrentDataStringVersion(results,hbReqInfo,handBookList);				
			}
			
		}
		return handBookList;
	}
	
	private List buildAllDataStringVersion(List results, HandBookRequestInfo hbReqInfo,List handBookList){
		
		for (Iterator iter = results.iterator(); iter.hasNext();) {
			DocumentReceipt docReceipt = (DocumentReceipt) iter
			.next();
			buildDataString(docReceipt,hbReqInfo,handBookList );
		}
		return handBookList;
		
	}
	
	private List buildCurrentDataStringVersion(List results, HandBookRequestInfo hbReqInfo,List handBookList){
		
		DocumentReceipt docReceipt = (DocumentReceipt) results.get(0);
		buildDataString(docReceipt,hbReqInfo,handBookList );
		return handBookList;
		
	}
	
	private List buildDataString(DocumentReceipt docReceipt,HandBookRequestInfo hbReqInfo, List handBookList){

		Set Plans = docReceipt.getPlans();
		HandBookInfo hbi = new HandBookInfo();
		hbi.setDocType("Data String");		
		hbi.setName("Data String");
		hbi.setReleaseControlNumber(docReceipt.getReleaseControlNumber());
		hbi.setVersion(docReceipt.getVersionNumber());	
		populateDataStringAndDate(Plans,docReceipt,hbi);		
		handBookList.add(hbi);
		return handBookList;
	}
	
	private void populateDataStringAndDate(Set Plans,DocumentReceipt docReceipt,HandBookInfo hbi){
		
		StringBuffer formMessageBody = new StringBuffer();
		String a = "F400H^" + docReceipt.getReceiptString()+ "^" + docReceipt.getVPIDValue();
		for (Iterator iter = Plans.iterator(); iter.hasNext();) {
			HealthBenefitPlan benefitPlan = (HealthBenefitPlan) iter
			.next();
			String b = "^" + benefitPlan.getHealthBenefitCategory()+"^"+benefitPlan.getHealthBenefitCode()+"^"+benefitPlan.getCoveragePlanCode() + '\n';
            formMessageBody.append(a);
            formMessageBody.append(b);
            hbi.setGeneratedDate(benefitPlan.getCreatedOn());
		}
		hbi.setConcatenatedString(formMessageBody);
		
	}
	
	/**
	 * Transform delivery preference into EESummary.
	 */
	public EESummary buildDeliveryPreferenceInfo(
			DeliveryPreference deliveryPreference) {
		EESummary summary = new EESummary();
		//as per ccr12068 -- return deliveryPreferenceInfo as not null eventhough deliveryprefernece is null
		DeliveryPreferenceInfo info = new DeliveryPreferenceInfo();
		if (deliveryPreference != null) {
			//DeliveryPreferenceInfo info = new DeliveryPreferenceInfo();
			if(deliveryPreference.getDeliveryPreferenceType() != null){
			info.setDeliveryPreference(deliveryPreference
					.getDeliveryPreferenceType().getName());
			}
			if(deliveryPreference.getDeliveryPreferenceEmail() != null){
				
			Set<DeliveryPreferenceEmail> emailSet = deliveryPreference
					.getDeliveryPreferenceEmail();
			for (DeliveryPreferenceEmail deliveryPreferenceEmail : emailSet) {
				EmailType emailType = deliveryPreferenceEmail.getType();
				if (emailType != null) {
					// if email type is not specified, leave email as NULL in info.
					if (emailType.getCode().equals("2")) {
						info.setEmailAddress(deliveryPreferenceEmail
								.getAddress());
						info.setEmailType("BUSINESS");
					} else if (emailType.getCode().equals("1")) {
						info.setEmailAddress(deliveryPreferenceEmail
								.getAddress());
						info.setEmailType("PRIVATE");
					}
				}
			}
		}
			//summary.setDeliveryPreferenceInfo(info);
		}
		summary.setDeliveryPreferenceInfo(info);
		return summary;
	}
	
	
	
}
