package gov.va.med.esr.vbr.webservice.impl;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


import javax.security.auth.login.LoginException;

import org.apache.commons.io.FileUtils;

//import gov.va.med.esr.service.DemographicService;
import gov.va.med.esr.common.batchprocess.HealthBenefitPlanData;
import gov.va.med.esr.common.model.CommonEntityKeyFactory;
import gov.va.med.esr.common.model.comms.DeliveryPreference;
import gov.va.med.esr.common.model.comms.Directory;
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.FileInfo;
import gov.va.med.esr.common.model.comms.HandBookMailQueue;
import gov.va.med.esr.common.model.comms.HealthBenefitPlan;
import gov.va.med.esr.common.model.lookup.ComLetterTemplateType;
import gov.va.med.esr.common.model.lookup.HandBookMailStatusType;
import gov.va.med.esr.common.model.lookup.VeteranIdentifierType;
import gov.va.med.esr.common.model.person.id.PersonIdEntityKey;
import gov.va.med.esr.service.HandBookService;
import gov.va.med.esr.service.LookupService;
import gov.va.med.esr.service.PersonService;
import gov.va.med.esr.service.external.EntityFinder;
import gov.va.med.esr.service.external.person.AbstractEntityFinder;
import gov.va.med.esr.service.external.person.DeliveryPreferenceInfo;
import gov.va.med.esr.service.external.person.VPIDEntityFinder;
import gov.va.med.esr.vbr.webservice.Audit;
import gov.va.med.esr.vbr.webservice.Message;
import gov.va.med.esr.vbr.webservice.RetrieveDocumentRequest;
import gov.va.med.esr.vbr.webservice.RetrieveDocumentResponse;
import gov.va.med.esr.vbr.webservice.SaveDocumentRequest;
import gov.va.med.esr.vbr.webservice.SaveDocumentResponse;
import gov.va.med.esr.vbr.webservice.SysOwnerType;
import gov.va.med.esr.vbr.webservice.VbrDocumentServiceEndpoint;
import gov.va.med.esr.vbr.webservice.VbrFault;
import gov.va.med.esr.vbr.webservice.VbrFaultException;
import gov.va.med.esr.vbr.webservice.VeteranIdentifier;
import gov.va.med.esr.vbr.webservice.ObjectFactory;
import gov.va.med.fw.model.UserPrincipalImpl;
import gov.va.med.fw.security.LoginManager;
import gov.va.med.fw.security.SecurityContextHelper;
import gov.va.med.fw.security.UserCredentials;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.service.config.SingletonApplicationContext;

import org.apache.log4j.Logger;

@javax.jws.WebService(endpointInterface = "gov.va.med.esr.vbr.webservice.VbrDocumentServiceEndpoint")

public class VbrSvcPortImpl extends AbstractComponent implements VbrDocumentServiceEndpoint {
 
   
	@Override
	
	 public SaveDocumentResponse saveDocumentInRepository(
		        SaveDocumentRequest saveDocumentRequest)
		        throws VbrFault{
		 String VBR_MESSAGE_INITIATER = "VCG";
		//LoginManager loginManager;
		ObjectFactory factory = new ObjectFactory();
		SaveDocumentRequest.Documents documents = new SaveDocumentRequest.Documents();
		Message msg = new Message();
		SaveDocumentResponse response = factory.createSaveDocumentResponse();
		
		// authentication
		
		try {
			processAuthenticate(VBR_MESSAGE_INITIATER);
		} catch (Exception ex) {
			logger.debug("VBR authentication exception: "
					+ ex.getMessage());
		}
		// Validation 
		if(saveDocumentRequest.getDocuments() != null){
			documents = saveDocumentRequest.getDocuments();
		}
		List <gov.va.med.esr.vbr.webservice.Document> documentList = null;
		if(documents.getDocument() != null){
		 documentList = documents.getDocument();
		}
		VeteranIdentifier identifier = null;
		if(saveDocumentRequest.getVeteranIdentifier() != null ){
			   identifier = saveDocumentRequest.getVeteranIdentifier();
		}
		HealthBenefitPlanData[]  healthPlanData = this.getHealthBenefitData(documentList);
		String deliveryPreference = null;
		boolean systemGeneratedDocType = false;
		systemGeneratedDocType = isSystemGeneratedDocType(documentList);
		if(saveDocumentRequest.getDeliveryPreference() != null && saveDocumentRequest.getDeliveryPreference().length() > 0){
			deliveryPreference = saveDocumentRequest.getDeliveryPreference();
		}
		// Validation
		ArrayList<String> validationError = validateSaveDocumentRequest(documentList,identifier, healthPlanData,deliveryPreference,systemGeneratedDocType);
		
		//check for validation error
		if( ( validationError.isEmpty() && validationError.size()<= 0 ) || validationError == null)	{
			try {
				  
				  saveDocumentRequest(documentList, healthPlanData,(identifier != null) ? identifier.getValue() : null);
				  
				  //CCR 12038
				  // if receipt number (HandbookrequestId)is null don't update the delivery preference
				  if(healthPlanData[0] != null && healthPlanData[0].getHandbookRequestId() != null && systemGeneratedDocType){
					  updateMailingStatus(deliveryPreference,healthPlanData[0].getHandbookRequestId());
				  }
				   response.setStatus("Success");
					msg.setType("Success");
					msg.setDetail("Request is successfully completed");
					response.setTimeStamp(response.getTimeStamp());	
					
	              } catch (Exception ex)
	              {
	 					response.setTimeStamp(this.getDateJavatoXML(new Date()));
	 					logger.error("Exception  :" , ex);
	 					ArrayList<String> arrList = new ArrayList<String>();
	 					arrList.add(ex.getMessage());
	 					VbrFaultException vbrFaultException = createException(arrList);	
	 					throw new VbrFault("Failure :VBR Save Document Exception",vbrFaultException);
	              }	
		} else{
			VbrFaultException vbrFaultException = createException(validationError);
			throw new VbrFault("Failure :VBR Save Document: Validation Error :",vbrFaultException);
		}
		response.setTimeStamp(this.getDateJavatoXML(new Date()));
		response.setMessage(msg);
		return response;
	}
	
	 public RetrieveDocumentResponse getDocumentFromRepository(
		        RetrieveDocumentRequest retrieveDocumentRequest)
		        throws VbrFault{
		ObjectFactory factory = new ObjectFactory();
		RetrieveDocumentResponse response = factory.createRetrieveDocumentResponse();
	//	List<gov.va.med.esr.vbr.webservice.DocumentType> documentTypes = retrieveDocumentRequest.getSearchCriteria().getTypes().getType();
	//	RetrieveDocumentResponse.Documents documents = new RetrieveDocumentResponse.Documents();
		
		Message msg = new Message();
		//Validation
		ArrayList<String> validationError = validateRetrievetDocumentRequest(retrieveDocumentRequest);
			if(validationError.isEmpty() && validationError.size()<= 0){
			
				try {
					List<gov.va.med.esr.vbr.webservice.DocumentType> documentTypes = retrieveDocumentRequest.getSearchCriteria().getTypes().getType();
					RetrieveDocumentResponse.Documents documents = new RetrieveDocumentResponse.Documents();
					VeteranIdentifier identifier = retrieveDocumentRequest.getSearchCriteria().getVeteranIdentifier();
	            	  String fileFormat = null;
	      			
	      			fileFormat= getFileTypeValue(retrieveDocumentRequest.getSearchCriteria().getFormat());
	      			
	      			
					HandBookService handbookService = (HandBookService)SingletonApplicationContext.getInstance()
    				.getSingletonContext().getBean("handBookService");
					
	            	  List <gov.va.med.esr.vbr.webservice.Document> documentList = documents.getDocument();
	            	  
	            	  List results = handbookService.getHandbookInformation(identifier.getValue());
	            	  int docId = 0;
	            	  if(results != null && !results.isEmpty()){
	            		 
	            		  for(gov.va.med.esr.vbr.webservice.DocumentType documentType: documentTypes){
	            			  
	            			  docId = getDocumentTypeId(documentType);
	            			//  docId=1;
	            			 
	            		     //  if( fileFormat.equalsIgnoreCase("xml") && (docId == 5 || docId == 3 )){
	            	  	  			documentList = buildDocumentResponse(results,documentList, docId,fileFormat);
	            	  	  	//	}
	            	  
	            	  		}
	            	    response.setDocuments(documents);
	                    response.setStatus("Success");
	 					msg.setType("Success");
	            	  }else{
	            		  response.setDocuments(null);
	            		  response.setStatus("Failure");
	            		  msg.setType("Failed");
	            		  msg.setDetail("No documents found for the VPID : " + identifier.getValue());
	            	  }
	 
	              } catch (Exception ex){
	 					response.setTimeStamp(this.getDateJavatoXML(new Date()));
	 					response.setDocuments(null);
	 					logger.error("Exception  :" , ex);
	 					ArrayList<String> arrList = new ArrayList<String>();
	 					arrList.add(ex.getMessage());
	 					VbrFaultException vbrFaultException = createException(arrList);	
	 					throw new VbrFault("Failure : VBR Retrieve Document Exception",vbrFaultException);
	              }
			
			}else {					
			response.setStatus("Failure");
			msg.setType("Failed");
			msg.setDetail("Validation Error :");
			response.setDocuments(null);
			VbrFaultException vbrFaultException = createException(validationError);
			throw new VbrFault("Failure :VBR Retrieve Document: Validation Error",vbrFaultException);
			}
			
			response.setTimeStamp(this.getDateJavatoXML(new Date()));
			response.setMessage(msg);
		return response;
	}
	
	private List<gov.va.med.esr.vbr.webservice.Document> buildDocumentResponse(List results, List <gov.va.med.esr.vbr.webservice.Document> documentList,int documentTypeId,String fileFormat) throws ServiceException{
		//DocumentReceipt docReceipt = (DocumentReceipt) results.get(0);
		boolean docType = false;
		int versionNumber = 0;
		
		for (Iterator iter = results.iterator(); iter.hasNext();) {
			DocumentReceipt docReceipt = (DocumentReceipt) iter	.next();
			versionNumber = docReceipt.getVersionNumber();
			Set Documents = docReceipt.getDocuments();
				for (Iterator iter1 = Documents.iterator(); iter1.hasNext();) {
				Document doc = (Document) iter1
				.next();
				
					if (doc.getDocumentType().getIdentifier().intValue()== documentTypeId) docType = true;
				}
			
					
			if(docType==true && versionNumber > 0){
			documentList = buildDocumentForType(docReceipt,documentList,documentTypeId,fileFormat );
			break;
			}
			
		}
		return documentList;
	}
	
	private List<gov.va.med.esr.vbr.webservice.Document> buildDocumentForType(DocumentReceipt docReceipt,List <gov.va.med.esr.vbr.webservice.Document> documentList ,int documentTypeId,String fileFormat) throws ServiceException{
		
		Set Documents = docReceipt.getDocuments();
		//File file;
		
		for (Iterator iter = Documents.iterator(); iter.hasNext();) {
			Document doc = (Document) iter
			.next();
			
			if(doc.getDocumentType().getIdentifier().intValue()== documentTypeId){
				gov.va.med.esr.vbr.webservice.Document document = new gov.va.med.esr.vbr.webservice.Document();
				//gov.va.med.esr.vbr.webservice.DocumentType dt = new gov.va.med.esr.vbr.webservice.DocumentType(doc.getDocumentType().getName());
				if(doc.getDocumentType().getIdentifier().intValue() == documentTypeId){
				//document.setType(gov.va.med.esr.vbr.webservice.DocumentType.BENEFITS_AT_A_GLANCE_SELF_GENERATED_BY_SYSTEM);
					setDocumentTypeValue(document, documentTypeId);
				}
				document.setName(doc.getFileInfo().getName());
				if(doc.getDocumentType().getFileFormat() != null ){
					setFileTypeValue(document,doc.getDocumentType().getFileFormat());
				}
				//document.setPhysicalLocation(doc.getFileInfo().getDirectory().getMountPoint().getName() + doc.getFileInfo().getDirectory().getName());
				//file = new File(doc.getFileInfo().getDirectory().getMountPoint().getName() + doc.getFileInfo().getDirectory().getName());
				//local testing
				Audit audit = new Audit();
                audit.setModifiedBy(SysOwnerType.VCG);
                audit.setCreatedBy(SysOwnerType.VCG);
                if(doc.getModifiedOn() != null)
                audit.setModifiedDate(getDateJavatoXML(doc.getModifiedOn()));
                if(doc.getCreatedOn() != null)
                audit.setCreatedDate(getDateJavatoXML(doc.getCreatedOn()));
                document.setAudit(audit);
               //local testing
                //String fileName = "C:\\Work\\Test\\myTestread.xml";
              //  document.setContent(readFileContent(fileName));
                try{
				document.setContent(readFileContent(doc.getFileInfo().getDirectory().getMountPoint().getName() + doc.getFileInfo().getDirectory().getName()+doc.getFileInfo().getName()));
                }catch(ServiceException ex){
                	throw new ServiceException(ex.getMessage());
                }
				document.setReleaseControlNumber(docReceipt.getReleaseControlNumber());
				document.setVersionNumber(docReceipt.getVersionNumber());
				documentList.add(document);	
			}			
		}
		  return documentList;
		
	}
	
	private int getDocumentTypeId(gov.va.med.esr.vbr.webservice.DocumentType documentType){
		int typeId= -1;
		
		if(gov.va.med.esr.vbr.webservice.DocumentType.HANDBOOK_SELF_GENERATED_BY_VETERAN.equals(documentType)) typeId=5 ;
		if(gov.va.med.esr.vbr.webservice.DocumentType.HANDBOOK_AUTO_GENERATED_BY_SYSTEM.equals(documentType)) typeId=3 ;
		if(gov.va.med.esr.vbr.webservice.DocumentType.BENEFITS_AT_A_GLANCE_SELF_GENERATED_BY_VETERAN.equals(documentType)) typeId=6 ;
		if(gov.va.med.esr.vbr.webservice.DocumentType.BENEFITS_AT_A_GLANCE_AUTO_GENERATED_BY_SYSTEM.equals(documentType)) typeId=4 ;
		if(gov.va.med.esr.vbr.webservice.DocumentType.HEALTH_BENEFITS_PLAN_DATA_STRING.equals(documentType)) typeId=0 ;
		
		return typeId;
		
	}
	private void setDocumentTypeValue(gov.va.med.esr.vbr.webservice.Document document, int typeId){
		if(typeId==5)
		document.setType(gov.va.med.esr.vbr.webservice.DocumentType.HANDBOOK_SELF_GENERATED_BY_VETERAN);
		if(typeId==3)
			document.setType(gov.va.med.esr.vbr.webservice.DocumentType.HANDBOOK_AUTO_GENERATED_BY_SYSTEM);
		if(typeId==6)
			document.setType(gov.va.med.esr.vbr.webservice.DocumentType.BENEFITS_AT_A_GLANCE_SELF_GENERATED_BY_VETERAN);
		if(typeId==4)
			document.setType(gov.va.med.esr.vbr.webservice.DocumentType.BENEFITS_AT_A_GLANCE_AUTO_GENERATED_BY_SYSTEM);
		if(typeId==0)
			document.setType(gov.va.med.esr.vbr.webservice.DocumentType.HEALTH_BENEFITS_PLAN_DATA_STRING);
		
	}
	private String getFileTypeValue(gov.va.med.esr.vbr.webservice.FormatType type) {
		String fileType=null;
	if(gov.va.med.esr.vbr.webservice.FormatType.XML.equals(type)) fileType="xml";
	if(gov.va.med.esr.vbr.webservice.FormatType.PDF.equals(type)) fileType="pdf";
	if(gov.va.med.esr.vbr.webservice.FormatType.TXT.equals(type)) fileType="txt";
	return fileType;
	}
	
	private void setFileTypeValue(gov.va.med.esr.vbr.webservice.Document document,String fileType) {
		
		if(fileType.equalsIgnoreCase("XML")) document.setFormat(gov.va.med.esr.vbr.webservice.FormatType.XML);
		if(fileType.equalsIgnoreCase("PDF")) document.setFormat(gov.va.med.esr.vbr.webservice.FormatType.PDF);
		if(fileType.equalsIgnoreCase("TXT")) document.setFormat(gov.va.med.esr.vbr.webservice.FormatType.TXT);
	}	
	
	private Date getDateXMLtoJava(javax.xml.datatype.XMLGregorianCalendar xdate){
		Date date = null;
		if(xdate != null){
			date= new Date(xdate.getMillisecond());
		}
		
		return date;
	}
	
	private javax.xml.datatype.XMLGregorianCalendar getDateJavatoXML(Date date){
		 GregorianCalendar gc = new GregorianCalendar();
         gc.setTime(date);
         javax.xml.datatype.XMLGregorianCalendar mdate = null;
         try{
         javax.xml.datatype.DatatypeFactory df = null;
         df = javax.xml.datatype.DatatypeFactory.newInstance();
         mdate = df.newXMLGregorianCalendar(gc);
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             logger.error("Exception @getDateJavatoXML  :" , e);
         }
		return mdate;
	}
	
	private byte[] readFileContent(String fileName)throws ServiceException{
		
		File file;
		byte [] content  = null;
		try{
			file = new File(fileName);
			//file = new File("C:\\Work\\Test\\myTestread.txt");
			content = new byte[(int) file.length()];
			if(file != null){
				//byte[] content1 = FileUtils.readFileToByteArray(file);
				//encode and send
				//content = Base64.encodeBase64(content1);
				content = FileUtils.readFileToByteArray(file);
				}
			}
			catch (FileNotFoundException ex){
				
				ex.printStackTrace();
				logger.error("Exception @readFileContent  :" , ex);
				throw new ServiceException("File Not Found :"+fileName);
			}
			catch(IOException iex){
				//
				iex.printStackTrace();
				logger.error("Exception @readFileContent  :" , iex);
				throw new ServiceException("File Read Error :"+fileName);
			}
			catch(Exception ex){
				//
				ex.printStackTrace();
				logger.error("Exception @readFileContent  :" , ex);
				throw new ServiceException("File Read Error :"+fileName);
			}
		
		return content;
		
	}
	
	private String writeFileContent(String fileName, byte[] content){
		String err = null;
		File file;
		try{
		file = new File(fileName);
		//file = new File("C:\\Work\\Test\\myTestwrite.xml");
		if(file != null){
				//decode and write
				//byte[] decode = Base64.decodeBase64(content);
				//FileUtils.writeByteArrayToFile(file,decode);
				FileUtils.writeByteArrayToFile(file,content);
			}
		}	
		catch (FileNotFoundException ex){
				err = "File Not Found : "+fileName;
				ex.printStackTrace();
				logger.error("Exception @writeFileContent  :" , ex);
		}
		catch(IOException iex){
				//
			err = "Failed to write file :" + fileName;
		}
		catch(Exception ex){
			//
			err = "Failed to write file :" + fileName;
			ex.printStackTrace();
			logger.error("Exception @writeFileContent  :" , ex);
		}
		return err;
	}

	private ArrayList<String> validateSaveDocumentRequest(List <gov.va.med.esr.vbr.webservice.Document> documentList, 
			VeteranIdentifier identifier,HealthBenefitPlanData[] healthBenefitPlanData,String deliveryPreference,boolean systemGeneratedDocType){
		ArrayList<String> validationError = new ArrayList<String>();
		String releaseControlNumber= null;
		String receiptNumber = null;
		//Audit audit = null;
		//boolean isValidDocType = false;
		// Validate Vetran Identifier
		ArrayList<String> identErr = validateVeteranIdentifier(identifier);
		
		ArrayList<String> docErr = validateDocument(documentList,deliveryPreference);
		
		if(!identErr.isEmpty())validationError.addAll(identErr);
		if(!docErr.isEmpty())validationError.addAll(docErr);
		
		//get receipt and release control number
		if(documentList != null){
				for (int i = 0; i < documentList.size(); i++) {
						gov.va.med.esr.vbr.webservice.Document doc = (gov.va.med.esr.vbr.webservice.Document)documentList.get(i);
								if(doc.getRequestNumber() != null && doc.getRequestNumber().trim().length()> 0 
										&& receiptNumber == null){
									receiptNumber = doc.getRequestNumber();
								}
								if(doc.getReleaseControlNumber() != null && doc.getReleaseControlNumber().trim().length()>0 && 
										releaseControlNumber == null){
									releaseControlNumber = doc.getReleaseControlNumber();
								}
					}
		}
		
		
		   // HealthBenefitPlanData validation;
		
		if(healthBenefitPlanData != null && healthBenefitPlanData.length > 0){
			if(healthBenefitPlanData[0] != null){
				for(int i=0; i<healthBenefitPlanData.length;i++){
					ArrayList<String> errors = validateBenefitData(healthBenefitPlanData[i],receiptNumber,releaseControlNumber,identifier.getValue(),systemGeneratedDocType);
			
					if(! errors.isEmpty())validationError.addAll(errors);
				}
			}else{ 
				validationError.add("Missing Health Benefit Data :");
			}
		} else{
			validationError.add("Missing Health Benefit Data :");
		}
		
		return validationError;
	}
	
	public void saveDocumentRequest(List <gov.va.med.esr.vbr.webservice.Document> documentList, 
			HealthBenefitPlanData[] healthBenefitPlanData,String vpid)
	throws ServiceException {
		
		 HandBookService handbookService = (HandBookService)SingletonApplicationContext.getInstance()
			.getSingletonContext().getBean("handBookService");
		 
        LookupService lookupService = (LookupService)SingletonApplicationContext.getInstance()
			.getSingletonContext().getBean("lookupService");
       
        //Get documenttype based on the id
        gov.va.med.esr.common.model.lookup.DocumentType handBookFileType = null;
        gov.va.med.esr.common.model.lookup.DocumentType benefitsProfileFileType = null;
        for (int i = 0; i < documentList.size(); i++) {
			gov.va.med.esr.vbr.webservice.Document doc = (gov.va.med.esr.vbr.webservice.Document)documentList.get(i);
  		  if(this.getDocumentTypeId(doc.getType()) == 1){
  			
  			  handBookFileType = (gov.va.med.esr.common.model.lookup.DocumentType) lookupService
  			  	.getByCode(gov.va.med.esr.common.model.lookup.DocumentType.class,
  			  		gov.va.med.esr.common.model.lookup.DocumentType.CODE_HANDBOOK_BY_CMS.getCode());
  		  }
  		  if(this.getDocumentTypeId(doc.getType()) == 3){
  			  handBookFileType = (gov.va.med.esr.common.model.lookup.DocumentType) lookupService
  			  	.getByCode(gov.va.med.esr.common.model.lookup.DocumentType.class,
  			  		gov.va.med.esr.common.model.lookup.DocumentType.CODE_HANDBOOK_BY_VCG.getCode());
  		  }
  		  if(this.getDocumentTypeId(doc.getType()) == 5){
  			handBookFileType = (gov.va.med.esr.common.model.lookup.DocumentType) lookupService
  				.getByCode(gov.va.med.esr.common.model.lookup.DocumentType.class,
  						gov.va.med.esr.common.model.lookup.DocumentType.CODE_HANDBOOK_BY_VET.getCode());
  		  }
  		
  		if(this.getDocumentTypeId(doc.getType()) == 2){
  		benefitsProfileFileType = (gov.va.med.esr.common.model.lookup.DocumentType) lookupService
  		.getByCode(gov.va.med.esr.common.model.lookup.DocumentType.class,
  				gov.va.med.esr.common.model.lookup.DocumentType.CODE_BENEFITS_PROFILE_BY_CMS.getCode());
  		}
  		if(this.getDocumentTypeId(doc.getType()) == 4){
  			benefitsProfileFileType = (gov.va.med.esr.common.model.lookup.DocumentType) lookupService
  			.getByCode(gov.va.med.esr.common.model.lookup.DocumentType.class,
  					gov.va.med.esr.common.model.lookup.DocumentType.CODE_BENEFITS_PROFILE_BY_VCG.getCode());
  	
  		}
  		if(this.getDocumentTypeId(doc.getType()) == 6){
  			benefitsProfileFileType = (gov.va.med.esr.common.model.lookup.DocumentType) lookupService
  			.getByCode(gov.va.med.esr.common.model.lookup.DocumentType.class,
  					gov.va.med.esr.common.model.lookup.DocumentType.CODE_BENEFITS_PROFILE_BY_VET.getCode());
  		}
  	  }
		
		
		List documentReiptList = handbookService.findDocumentReceipts(vpid);
		// 
		String receiptNumber = null;
		String releaseControlNumber = null;
		if(healthBenefitPlanData[0] != null){
			if(healthBenefitPlanData[0].getHandbookRequestId() != null)receiptNumber = healthBenefitPlanData[0].getHandbookRequestId();
			if(healthBenefitPlanData[0].getReleaseControlNumber() != null)releaseControlNumber = healthBenefitPlanData[0].getReleaseControlNumber();
		}
		
		Directory currentDirectory = handbookService.findActiveVBRDirectory();
		
		String vbrFolderName = handbookService.getVBRFileLocation(currentDirectory);
		File vbrFolder  = new File(vbrFolderName);
		if ( ! vbrFolder.exists() ) {
			if ( !vbrFolder.mkdirs() ) {
				logger.error("Unable to Create VBR Folder :" + vbrFolderName);
				throw new ServiceException("Unable to Create VBR Folder :" + vbrFolderName);
			}
		}

		
		DocumentReceipt currentReceipt = null;
		int maxVersion = 0;
		
		List deleteReceipts = new ArrayList();

		for (int i = 0; i < documentReiptList.size(); i++) {
			DocumentReceipt receipt = (DocumentReceipt) documentReiptList
			.get(i);
			if(receiptNumber != null){
				if (receiptNumber.equals(receipt.getReceiptString())) {
					currentReceipt = receipt;
					
				}
			}
			if (maxVersion < receipt.getVersionNumber()) {
				maxVersion = receipt.getVersionNumber();
				
			}

			/**
			 * documentReiptList is ordered by version number desc. So we can
			 * delete the older version at the end of the list.
			 */
			
			if ((handBookFileType != null) && ((i + 1) >= handBookFileType.getVersionsKept())) {
				
				deleteReceipts.add(receipt);
				
			}
		}
		
		 int newVersionNumber = maxVersion + 1;
		boolean newDocumentReceipt = false;
		if (currentReceipt == null) {
			newDocumentReceipt = true;
			// get the documentReceipt by documentreceiptNumber. if not
			// found create a new Object.
			
			currentReceipt = new DocumentReceipt();
			currentReceipt.setReceiptDate(new Date());
			
			if(releaseControlNumber != null) {
				currentReceipt.setReleaseControlNumber(releaseControlNumber);	
			}
			currentReceipt.setVPIDValue(vpid);
			if(receiptNumber != null){
			currentReceipt.setReceiptString(receiptNumber);
			}
			currentReceipt.setVersionNumber(newVersionNumber);
			currentReceipt
			.setVeteranIdentifierType((VeteranIdentifierType) lookupService
					.getByName(VeteranIdentifierType.class, "VPID"));
			
			for (Iterator iter = documentList.iterator(); iter.hasNext();) {
				gov.va.med.esr.vbr.webservice.Document doc= (gov.va.med.esr.vbr.webservice.Document)iter.next();
				int docTypeId = getDocumentTypeId(doc.getType());
				Audit audit = doc.getAudit();
				
				String fileFormat = this.getFileTypeValue(doc.getFormat());
				
				if( docTypeId > 0 || ! fileFormat.equalsIgnoreCase("txt")){
				if( (docTypeId == 5 || docTypeId == 3 ) && fileFormat.equalsIgnoreCase("xml")){
					// Create the handbook document.
					
					Document handBookDoc = new Document();
					handBookDoc.setDocumentType(handBookFileType);
					handBookDoc.setCreationDate(new Date());
					FileInfo handBookFile = new FileInfo();
					handBookFile.setName(vpid
							+ "_HANDBOOK_V" + newVersionNumber + "."+fileFormat);
					handBookFile.setDirectory(currentDirectory);
					handBookDoc.setFileInfo(handBookFile);
					if(audit != null){
						
						if(audit.getCreatedBy() != null && audit.getCreatedBy().equals("VCG")) handBookDoc.setCreatedBy(new UserPrincipalImpl("VCG"));
						if(audit.getModifiedBy() != null && audit.getModifiedBy().equals("VCG"))handBookDoc.setModifiedBy(new UserPrincipalImpl("VCG"));
						if(audit.getModifiedDate() != null) handBookDoc.setModifiedOn(this.getDateXMLtoJava(audit.getModifiedDate()));
						if(audit.getCreatedDate() != null) handBookDoc.setCreationDate(this.getDateXMLtoJava(audit.getCreatedDate()));
						
					}
					currentReceipt.addDocument(handBookDoc);
					//local testing
					  //readFileContent("C:\\Work\\Test\\myTestread.xml");
					//writeFileContent("C:\\Work\\Test\\"+handBookFile.getName(), doc.getContent());
					//System.out.println("directory name :"+handBookDoc.getFileInfo().getDirectory().getMountPoint().getName() + handBookDoc.getFileInfo().getDirectory().getName());
					//System.out.println("file name :"+handBookDoc.getFileInfo().getDirectory().getMountPoint().getName() + handBookDoc.getFileInfo().getDirectory().getName()+handBookFile.getName());
					
					String err =writeFileContent(handBookDoc.getFileInfo().getDirectory().getMountPoint().getName() + handBookDoc.getFileInfo().getDirectory().getName()+handBookFile.getName(), doc.getContent());
					if(err != null) {
						throw new ServiceException(err);
					}
					
				}
				if((docTypeId == 6 || docTypeId == 4) && fileFormat.equalsIgnoreCase("pdf")){
					
					// Create Benefits Profile document.
					Document benefitsDoc = new Document();	
					benefitsDoc.setDocumentType(benefitsProfileFileType);

					FileInfo benefitsFile = new FileInfo();
					benefitsFile.setName(vpid
							+ "_BENEFITS_PROFILE_V" + newVersionNumber + "."+fileFormat);
					benefitsFile.setDirectory(currentDirectory);
					benefitsDoc.setFileInfo(benefitsFile);
					benefitsDoc.setCreationDate(new Date());
					
					if(audit != null){
						
						if(audit.getCreatedBy() != null && audit.getCreatedBy().equals("VCG")) benefitsDoc.setCreatedBy(new UserPrincipalImpl("VCG"));
						if(audit.getModifiedBy() != null && audit.getModifiedBy().equals("VCG"))benefitsDoc.setModifiedBy(new UserPrincipalImpl("VCG"));
						if(audit.getModifiedDate() != null) benefitsDoc.setModifiedOn(this.getDateXMLtoJava(audit.getModifiedDate()));
						if(audit.getCreatedDate() != null) benefitsDoc.setCreationDate(this.getDateXMLtoJava(audit.getCreatedDate()));
						
					}
					currentReceipt.addDocument(benefitsDoc);
					//local testing
					//byte[] content = readFileContent("C:\\Work\\Test\\myTestread.pdf");
					//writeFileContent("C:\\Work\\Test\\" + benefitsFile.getName(), doc.getContent());
					
					//System.out.println("benefit dir :"+benefitsDoc.getFileInfo().getDirectory().getMountPoint().getName() + benefitsDoc.getFileInfo().getDirectory().getName());
					//System.out.println("file name :"+benefitsDoc.getFileInfo().getDirectory().getMountPoint().getName() + benefitsDoc.getFileInfo().getDirectory().getName()+benefitsFile.getName());
					
					String err = writeFileContent(benefitsDoc.getFileInfo().getDirectory().getMountPoint().getName() + benefitsDoc.getFileInfo().getDirectory().getName()+benefitsFile.getName(), doc.getContent());
					if(err != null) {
						throw new ServiceException(err);
					}
					
				}
				
				if(audit != null){
					if(audit.getCreatedBy() != null && audit.getCreatedBy().equals("VCG")) currentReceipt.setCreatedBy(new UserPrincipalImpl("VCG"));
					if(audit.getModifiedBy() != null && audit.getModifiedBy().equals("VCG"))currentReceipt.setModifiedBy(new UserPrincipalImpl("VCG"));
					if(audit.getModifiedDate() != null) currentReceipt.setModifiedOn(this.getDateXMLtoJava(audit.getModifiedDate()));
					if(audit.getCreatedDate() != null) currentReceipt.setReceiptDate(this.getDateXMLtoJava(audit.getCreatedDate()));
				}
				}// if id=0
			}  ///for
			
			
			
		//}  //if
		
		
		for(int i=0; i < healthBenefitPlanData.length; i++){
			if (healthBenefitPlanData[i] != null){
			HealthBenefitPlan hbPlan = new HealthBenefitPlan();
			hbPlan
			.setHealthBenefitCategory(healthBenefitPlanData[i]
					.getCategoryCode());
			hbPlan.setCoveragePlanCode(healthBenefitPlanData[i].getCoveragePlanCode());
			hbPlan.setHealthBenefitCode(healthBenefitPlanData[i]
					.getHealthBenefitCode());
			currentReceipt.addHealthBenefitPlan(hbPlan);
					
			}
		}
		// save the receipt
	    // created method to update the new date(). JAX-WS sets XMLGregorian Calendar year..
		handbookService.saveOnlineDocumentReceipt(currentReceipt);
		//handbookService.saveDocumentReceipt(currentReceipt);
	//IF currentReceipt == null	
	}else {
		throw new ServiceException("The handbook artifacts for this request number already exists in VBR. Therefore request will not be saved into VBR");
	}
		
   
		// Only do this incase of a new documentreceipt record. No need to
		// do this after the first record is processed.
		// 1. Move the pdf files from current location to the VBR folder.
		// 2a. Delete the older versions if they are more than 3 versions
		// old.[from the table]
		// 2b. Delete old version pdf files from the VBR folder.
	//As per CCR 12154 the following code is commented out --as it violates document_accees_log constraint
	// As per 12155 added dcoumentAccessLog deletion...	
		
		if (newDocumentReceipt) {
			for (int j = 0; deleteReceipts != null && j < deleteReceipts.size(); j++) {
				DocumentReceipt receipt = (DocumentReceipt) deleteReceipts
				.get(j);
				Set delDocs = receipt.getDocuments();
				// Before deleting document receipt, delete the documentAccess log entry..
			  //CCR12155
			       	handbookService.deleteDocumentReceipt(receipt);
			
				if (delDocs != null && delDocs.size() > 0) {
					Iterator delDocItr = delDocs.iterator();
					while (delDocItr.hasNext()) {
						Document delDoc = (Document) delDocItr.next();
						FileInfo file = delDoc.getFileInfo();
						File phyFile = null;
						try {	
							phyFile = new File(handbookService.getVBRFileLocation(file
									.getDirectory())
									+ file.getName());
						} catch (Exception e) {
							// do not fail on exception/
						}

						if (phyFile != null && !phyFile.delete()) {
							// may be log and continue....
						}
					}
				}
				
			} 
		}
		
	//}
		
		
	}


private ArrayList<String> validateRetrievetDocumentRequest(RetrieveDocumentRequest retrieveDocumentRequest){
		
		String fileFormat = null;
		int documentTypeId =0;
		ArrayList<String> validationError = new ArrayList<String>();
		// Validate Veteran Identifier
		VeteranIdentifier identifier = null;
		if(retrieveDocumentRequest.getSearchCriteria() != null){
		if(retrieveDocumentRequest.getSearchCriteria().getVeteranIdentifier() != null){
		        identifier = retrieveDocumentRequest.getSearchCriteria().getVeteranIdentifier();
		        ArrayList<String> identErr = validateVeteranIdentifier(identifier);
		        if(!identErr.isEmpty() || identErr.size() > 0){
					validationError.addAll(identErr);
				}
		}else{
			validationError.add("Missing Veteran Data :");
		}
	
		// validate file foramt
		if(retrieveDocumentRequest.getSearchCriteria().getFormat() != null && retrieveDocumentRequest.getSearchCriteria().getFormat().value().trim().length() > 0){
			fileFormat = getFileTypeValue(retrieveDocumentRequest.getSearchCriteria().getFormat());	
			}
		//file format is optional
		
		// validate doc types
		if(retrieveDocumentRequest.getSearchCriteria().getTypes() != null && retrieveDocumentRequest.getSearchCriteria().getTypes().getType()!= null){
		List<gov.va.med.esr.vbr.webservice.DocumentType> documentTypes = retrieveDocumentRequest.getSearchCriteria().getTypes().getType();
				for(gov.va.med.esr.vbr.webservice.DocumentType documentType: documentTypes){
					documentTypeId = getDocumentTypeId(documentType);
					if(  !(documentTypeId == 5 || documentTypeId == 3 || documentTypeId ==6 
							|| documentTypeId==4 )){
						validationError.add("Invalid Document type:" );
					}
					if( (documentTypeId == 5 || documentTypeId == 3)){ 
							if(fileFormat != null && ! fileFormat.equalsIgnoreCase("xml")){
								validationError.add("Invalid file format : docType :" +documentType+ " : File Format :"+ fileFormat );
							}
					}
					if( (documentTypeId == 6 || documentTypeId == 4)){
						if(fileFormat != null  && ! fileFormat.equalsIgnoreCase("pdf")){
						validationError.add("Invalid file format: docType :" +documentType + " : File Format :"+ fileFormat);
						}
					}
					
				}
			
			}else{
				validationError.add("Missing document Type :" );
		}
		}else{
			validationError.add("Missing Search Criteria :");
		}
	
		 return validationError;
	}
	
private ArrayList<String> validateBenefitData(HealthBenefitPlanData healthBenefitPlanData, 
		String receiptNumber, String releaseControlNumber, String vpid,boolean systemGeneratedDocType){
	String[] validProductIds = {"H400H", "H400B", "H400F"};
	ArrayList<String> errors = new ArrayList<String>();
	if(healthBenefitPlanData != null){
	if ( healthBenefitPlanData.getProductID() == null || healthBenefitPlanData.getProductID().length() <= 0 ) {
		errors.add("Missing Required field: ProductId");
	} else {
		List list = Arrays.asList(validProductIds);
		if ( ! list.contains(healthBenefitPlanData.getProductID()) )
		{
			errors.add("Invalid ProductId: " + healthBenefitPlanData.getProductID());
		}
	}
	if(receiptNumber != null){
		
		if ( healthBenefitPlanData.getHandbookRequestId() == null || healthBenefitPlanData.getHandbookRequestId().length() <= 0 ) {
		errors.add("Missing Required field: HandbookRequestId");
		
		}else{
			
				 if(!healthBenefitPlanData.getHandbookRequestId().equalsIgnoreCase(receiptNumber))
						errors.add("More than one HandbookRequestId : ");
		}			
	} else{
			if (  healthBenefitPlanData.getHandbookRequestId() != null ) {
				errors.add("Benefit String request id is not matching with the request number:");
			}
	}
	
	if ( healthBenefitPlanData.getReleaseControlNumber() == null || healthBenefitPlanData.getReleaseControlNumber().length() <= 0 ) {
		errors.add("Missing Required field: ReleaseControlId");
	}
	if ( healthBenefitPlanData.getReleaseControlNumber() != null && releaseControlNumber != null &&
			!healthBenefitPlanData.getReleaseControlNumber().equalsIgnoreCase(releaseControlNumber) ){
		errors.add("ReleaseControlId : More than one release control number");
	}
	
	
	if ( healthBenefitPlanData.getIcn() == null || healthBenefitPlanData.getIcn().length() <= 0 ) {
		errors.add("Missing Required field: Unique Identifier for the Veteran");
		
	}else {
			if(vpid != null && !vpid.trim().equalsIgnoreCase(healthBenefitPlanData.getIcn().trim())){
				errors.add("Veteran Identifier: Different in benefit string");
			}
			
		}
	
	if ( healthBenefitPlanData.getHealthBenefitCode() == null || healthBenefitPlanData.getHealthBenefitCode().length() <= 0 ) {
		errors.add("Missing Required field: Benefit Code");
	}
	
	if ( healthBenefitPlanData.getCategoryCode() == null || healthBenefitPlanData.getCategoryCode().length() <= 0 ) {
		errors.add("Missing Required field: Benefits Categoty Code ");
	}
	
	if ( healthBenefitPlanData.getCoveragePlanCode() == null || healthBenefitPlanData.getCoveragePlanCode().length() <= 0 ) {
		errors.add("Missing Required field: Coverage Plan Code ");
	}
	
	PersonIdEntityKey personId =null; 
	HandBookMailQueue mailQueue = null;
	String releaseContrl = null;
	if ( healthBenefitPlanData.getIcn() != null ) {
		try{
		//check if the VPID is valid. 
			PersonService personService= (PersonService)SingletonApplicationContext.getInstance()
			.getSingletonContext().getBean("personService");
			personId = personService.getPersonIdByVPID( CommonEntityKeyFactory.createVPIDEntityKey(healthBenefitPlanData.getVpid()));
			if(receiptNumber != null && healthBenefitPlanData.getHandbookRequestId() != null && systemGeneratedDocType){
			HandBookService handBookService= (HandBookService)SingletonApplicationContext.getInstance()
			.getSingletonContext().getBean("handBookService");
			
			 mailQueue = handBookService.findHandBookByIdentifier(healthBenefitPlanData.getHandbookRequestId());
			}
			//online veteran generated doc..
			if(!systemGeneratedDocType){
				HandBookService handBookService= (HandBookService)SingletonApplicationContext.getInstance()
				.getSingletonContext().getBean("handBookService");
				releaseContrl= handBookService.getHandBookReleaseControl(null).getCode();
				
			}

		} catch ( ServiceException e) {
			//e.printStackTrace();
			//throw e;
		}
		if ( personId == null ) {
			errors.add("Invalid ICN :" + healthBenefitPlanData.getIcn());
		}
		if(receiptNumber != null && healthBenefitPlanData.getHandbookRequestId() != null && systemGeneratedDocType){
		if ( mailQueue == null ) {
			errors.add("Invalid HandBookRequestId :" + healthBenefitPlanData.getHandbookRequestId());
		} else {
			//check if the person id mataches 
			if ((personId != null) && (! personId.getKeyValue().equals(mailQueue.getPersonId()))) {
				errors.add("Invalid ICN, ICN does not match the HandBookRequestId :" + healthBenefitPlanData.getIcn());
			}
			
			
			if (! mailQueue.getHandBookReleaseControl().getCode().equals(healthBenefitPlanData.getReleaseControlNumber())) {
				errors.add("Invalid Release Control ID, Does not match the request :" + healthBenefitPlanData.getReleaseControlNumber());
			}
		}
		}
		if(!systemGeneratedDocType){
			
			if(releaseContrl != null){
				if( !releaseContrl.trim().equalsIgnoreCase(healthBenefitPlanData.getReleaseControlNumber().trim())){
				errors.add("Invalid Release Control ID, does not match the default release control number in the system parameter : " + releaseContrl +" value in request :"+healthBenefitPlanData.getReleaseControlNumber());
				}
			}else{
				errors.add("Release Control number does not exsit in the System :" + releaseContrl);
			}
		}
	}

	}  //if health benefit data 
	return errors;
}

  
  
  private HealthBenefitPlanData[] getHealthBenefitData(List <gov.va.med.esr.vbr.webservice.Document> documentList){
	  byte[] content1 = null;
	  String content = null;
	  HealthBenefitPlanData[] healthBenefitPlanData = null;
	  if(documentList != null){
				for (int i = 0; i < documentList.size(); i++) {
				gov.va.med.esr.vbr.webservice.Document doc = (gov.va.med.esr.vbr.webservice.Document)documentList.get(i);
				 int documentTypeId= this.getDocumentTypeId(doc.getType());		
				if (documentTypeId == 0) content1= doc.getContent();
								
		}
	  }
	  if(content1 != null){
			//byte[] cont1decode = Base64.decodeBase64(content1);
			//content = new String(cont1decode);
		  content = new String(content1);
			}
		
			//The following lines are for information for local testing
	  //		content = "H400H^^1^0000001004255109V512731000000^Eye^EN01^EN01001";  -- online
		//	content = "H400H^373351326^1^0000001004255109V512731000000^Eye^EN01^EN01001";  --- batch
	    	/**
	    	 * ProductID^HandbookRequestId^releasecontrolnumber^VPID^CategoryCode^HealthBenefitCode^CoveragePlanCode
	    	F400H ^123456789^1^2004341118V132456^Enrollment^EN01^EN01001
	    	F400H ^123456789^1^2004341118V132456^Dental^DN01^DN01001
	    	F400H ^123456789^1^2004341118V132456^EyeGlasses^EY01^EY01001
	    	private String productID;
	    	private String handbookRequestId;
	    	private String vpid;
	    	private String categoryCode;
	    	private String healthBenefitCode;
	    	private String coveragePlanCode; 
	    	private String releaseControlNumber;
	    	**/
		//	String content = "F400H ^123456789^2004341118V132456^Enrollment^EN01^EN01001";
			
			
			if(content != null){
			String[] lines = org.apache.commons.lang.StringUtils.split(content, "\n");
			if(lines != null ){
			healthBenefitPlanData = new HealthBenefitPlanData[lines.length];
				for(int i=0; i<lines.length;i++){
					if(lines[i] != null && lines[i].trim().length() >0){
					String[] token = org.apache.commons.lang.StringUtils.split(lines[i], "^");
					healthBenefitPlanData[i] = null;
					if( token != null && token.length == 7){
						healthBenefitPlanData[i] = new HealthBenefitPlanData(); 
						  healthBenefitPlanData[i].setProductID(token[0]);
							if(token[1] != null && !token[1].trim().isEmpty()) {
								healthBenefitPlanData[i].setHandbookRequestId(token[1]);
							}else{
								healthBenefitPlanData[i].setHandbookRequestId(null);
							}
								
							healthBenefitPlanData[i].setReleaseControlNumber(token[2]);
							//set the long vpid...
							if(!token[3].startsWith("000000") || !token[3].endsWith("000000")){
									token[3] = (new StringBuilder("000000")).append(token[3]).append("000000").toString();
							}
							healthBenefitPlanData[i].setIcn(token[3]);
							healthBenefitPlanData[i].setCategoryCode(token[4]);
							healthBenefitPlanData[i].setHealthBenefitCode(token[5]);
							healthBenefitPlanData[i].setCoveragePlanCode(token[6]);
					}
				//for online request id will be null, so number of tokens will be 6. 
				// Adjacent separator/delimiters are treated as one : ^^
					if( token != null && token.length == 6){
						healthBenefitPlanData[i] = new HealthBenefitPlanData();
						healthBenefitPlanData[i].setProductID(token[0]);
					    // for online  requeset id is null
						healthBenefitPlanData[i].setHandbookRequestId(null);
							
						healthBenefitPlanData[i].setReleaseControlNumber(token[1]);
						//set the long vpid...
						if(!token[2].startsWith("000000") || !token[2].endsWith("000000")){
								token[2] = (new StringBuilder("000000")).append(token[2]).append("000000").toString();
						}
						healthBenefitPlanData[i].setIcn(token[2]);
						healthBenefitPlanData[i].setCategoryCode(token[3]);
						healthBenefitPlanData[i].setHealthBenefitCode(token[4]);
						healthBenefitPlanData[i].setCoveragePlanCode(token[5]);
				} 
					//if number of token less than required, only set the first token and during validation, error will be thrown 
				if( token != null && token.length >= 1 && token.length <= 5){
						healthBenefitPlanData[i] = new HealthBenefitPlanData();
						if(token[0] != null ){
							healthBenefitPlanData[i].setProductID(token[0]);
						}else{
							healthBenefitPlanData[i].setProductID(null);
						}
				}  // if
				
				} //if after for
			}   //For loops
			}  //lines
			}   //content
	  return healthBenefitPlanData;
	  
  }
  
  private void processAuthenticate(String logicalID) throws LoginException {
		UserCredentials creds = new UserCredentials();
		creds.setAnonymous(true);
		creds.setLogicalID(logicalID);
	//	LoginManager loginManager;
		SecurityContextHelper.initSecurityContextOnThread(getLoginManager(),
				creds);
	}
  
  public LoginManager getLoginManager() {
	  LoginManager loginManager = null;
		if (loginManager == null) {
			loginManager = (LoginManager) SingletonApplicationContext
					.getInstance().getSingletonContext()
					.getBean("edbLoginManager");
		}

		return loginManager;
	}
  
  private ArrayList<String> validateVeteranIdentifier(VeteranIdentifier identifier){
	  ArrayList<String> err = new ArrayList<String>();
	  if(identifier != null){
	  if ( identifier.getValue() == null || identifier.getValue().trim().length() <= 0) {
		  err.add("Missing Required field: Unique Identifier for the Veteran");
		}else{
			if( ! identifier.getValue().matches("[0]{6}[0-9]{10}V[0-9]{6}[0]{6}")){
				err.add("Invalid Veteran Id: " + identifier.getValue() );
			}
		}
		if(identifier.getType() == null || identifier.getType().length() <=0 ){
			err.add("Missing Required field : VeteranId Type " );
		}else{
			if( ! identifier.getType().equalsIgnoreCase("VPID")){
				err.add("Invalid VeteranId Type: " + identifier.getType() );
			}
		}
	  }else{
			err.add("Missing Veteran Data :");
		}
	  return err;
  }
  
  private ArrayList<String> validateDocument(List <gov.va.med.esr.vbr.webservice.Document> documentList, String deliveryPreference){
	  ArrayList<String> err = new ArrayList<String>();
		boolean isXMLfile = false;
		boolean isPDFfile = false;
		boolean isTXTfile = false;
	  if(documentList != null && documentList.size() == 3){
			int[] documentTypeId = new int[documentList.size()];
			int[] docTypes = new int[documentList.size()];
			 String [] fileType = new String[documentList.size()];
			 String [] releaseControlNumber = new String[documentList.size()];
			 String [] receiptNumber = new String[documentList.size()];
				for (int i = 0; i < documentList.size(); i++) {
						gov.va.med.esr.vbr.webservice.Document doc = (gov.va.med.esr.vbr.webservice.Document)documentList.get(i);
								if(doc.getType() != null) {
									documentTypeId[i]= this.getDocumentTypeId(doc.getType());
									if(documentTypeId[i] == -1){
										err.add("Invalid document type :"+ doc.getType());
									}
								} else{
									documentTypeId[i] = -1;
									err.add("Missing document type");
								}
								if(doc.getFormat() != null ) {
								fileType[i] = this.getFileTypeValue(doc.getFormat());
									if(fileType[i] == null){
										err.add("Invalid file format :" + doc.getFormat());
									}else{
										if(fileType[i].equalsIgnoreCase("xml")) isXMLfile = true;
										if(fileType[i].equalsIgnoreCase("pdf")) isPDFfile= true;
										if(fileType[i].equalsIgnoreCase("txt")) isTXTfile=true;
									}
								}else{
									fileType[i] = null;
									err.add("Missing file Format :");
								}
								// Request number may be null
								
								if(doc.getRequestNumber() != null && doc.getRequestNumber().trim().length()> 0 ){
									receiptNumber[i] = new String(doc.getRequestNumber());
								}else{
									receiptNumber[i]=null;
								}
								//audit validation
								if(doc.getAudit() == null){
									err.add("Missing Audit data : ");
								}
								// release number may not be null
								if(doc.getReleaseControlNumber() != null && doc.getReleaseControlNumber().trim().length()>0 ){
									releaseControlNumber[i] = new String(doc.getReleaseControlNumber());
								}else {
									releaseControlNumber[i]= null;
									err.add("Missing release control number : ");
								}
								
								if( (documentTypeId[i] == 5 || documentTypeId[i] == 3)){ 
									 docTypes[0] = documentTypeId[i];
										if(fileType[i] != null && ! fileType[i].equalsIgnoreCase("xml")){
											err.add("Invalid Document Types/File Types  :" + fileType[i]);
										}
								}
								if( (documentTypeId[i] == 6 || documentTypeId[i] == 4)){
									docTypes[1] = documentTypeId[i];
									if(fileType[i] != null && ! fileType[i].equalsIgnoreCase("pdf")){
									 err.add("Invalid Document Types/File Types :" +fileType[i]);
									}
								}
								if( documentTypeId[i] == 0 ){
									docTypes[2] = documentTypeId[i];
									if(fileType[i] != null && ! fileType[i].equalsIgnoreCase("txt")){
									 err.add("Invalid Document Types/File Types :" +fileType[i]);
									}
								}
								
								if(doc.getContent() == null || doc.getContent().length <= 0){
									err.add("Document content is Empty:"+ doc.getName());
								}
				} // for
				
				//validate receipt numbers
				if(receiptNumber[0] != null && receiptNumber[1] != null && receiptNumber[2] !=null){
					if( !receiptNumber[0].equalsIgnoreCase(receiptNumber[1])) err.add("Receipt numbers are different");
					if( !receiptNumber[0].equalsIgnoreCase(receiptNumber[2])) err.add("Receipt numbers are different");
					if( !receiptNumber[1].equalsIgnoreCase(receiptNumber[2])) err.add("Receipt numbers are different");
				}
					//validate release control number
				if(releaseControlNumber[0] != null && releaseControlNumber[1] != null && releaseControlNumber[2] !=null){
					if( !releaseControlNumber[0].equalsIgnoreCase(releaseControlNumber[1])) err.add("ReleaseControl Number are different");
					if( !releaseControlNumber[0].equalsIgnoreCase(releaseControlNumber[2])) err.add("Release Control Number are different");
					if( !releaseControlNumber[1].equalsIgnoreCase(releaseControlNumber[2])) err.add("Release Control Number are different");
				}
				//file format validation 
				if(!isXMLfile || !isPDFfile || !isTXTfile){
					err.add("File format error :");
				}
				//validate the correct doctypes for online or batch/system gnenerated
				// system/batch 3 4 0, online/vertean generated 5 6 0
				if( (docTypes[0] == 5 && docTypes[1] == 6 ) || (docTypes[0] == 3 && docTypes[1] == 4 )){
					// no error
				}else{
					err.add(" Online and System generated documents types should not mix: ");
				}
				//System generated document should have receipt number and delivery preference
				
				if( docTypes[0] == 3 && docTypes[1] == 4){
					
					if(receiptNumber[0] == null ){
						err.add(" Missing Receipt Number for system generated documents ");
					}
					
					if(deliveryPreference != null ){
						if(deliveryPreference.equalsIgnoreCase("MAIL") || deliveryPreference.equalsIgnoreCase("ONLINE")){
							//valid
						}else{
							err.add("Invalid Delivery Preference :" + deliveryPreference);
						}
					}else{
						err.add(" Missing delivery preference for system generated documents ");
					}
					
				}
				
		}else {
			
			err.add("Missing documents or Insufficient/More Documents: " );
		}
	  
		
	  return err;
  }
  private VbrFaultException createException(ArrayList<String> errList){
	  ObjectFactory factory = new ObjectFactory();
		VbrFaultException vbrFaultException = factory
		.createVbrFaultException();
		VbrFaultException.FaultExceptions faultExceptions = factory
		.createVbrFaultExceptionFaultExceptions();
		for (Iterator iter = errList.iterator(); iter.hasNext();) {
			String err = (String) iter.next();
			VbrFaultException.FaultExceptions.FaultException faultException = factory
			.createVbrFaultExceptionFaultExceptionsFaultException();
			faultException.setCode("Failed :");
			faultException.setMessage(err);
			faultExceptions.getFaultException().add(faultException);
			
		}
		vbrFaultException.setFaultExceptions(faultExceptions );
		 return vbrFaultException;
  }
 
  private void updateMailingStatus(String deliveryPreference,String receiptNumber){
	  
	  if(deliveryPreference != null ){
	  try{
		  HandBookService handbookService = (HandBookService)SingletonApplicationContext.getInstance()
			.getSingletonContext().getBean("handBookService");
		  LookupService lookupService = (LookupService) SingletonApplicationContext
			.getInstance().getSingletonContext().getBean(
					"lookupService");
		// order by handbookmailqueue_id 
		  
		HandBookMailQueue handbookMailQueue = handbookService.findHandBookByIdentifier(receiptNumber);
		//742-400H
		String formNumber = ComLetterTemplateType.FORM_NUMBER_400H.getCode();
		if(handbookMailQueue != null ){
			if(deliveryPreference.equalsIgnoreCase("ONLINE") && handbookMailQueue.getTemplate().getCommsTemplateFormNumber().equalsIgnoreCase(formNumber)) {
				
				handbookService.changeHandbookMailingStatus(handbookMailQueue,(HandBookMailStatusType)lookupService.getHandBookMailingStatusTypeByCode(HandBookMailStatusType.ONLINE.getCode()));
			}
		}
	  }catch(Exception e){
		  //
	  }
	  }
  }
  private boolean isSystemGeneratedDocType(List <gov.va.med.esr.vbr.webservice.Document> documentList){
	  boolean systemGeneratedDocType = false;
	  if(documentList != null){
	  for (int i = 0; i < documentList.size(); i++) {
			gov.va.med.esr.vbr.webservice.Document doc = (gov.va.med.esr.vbr.webservice.Document)documentList.get(i);
			if(this.getDocumentTypeId(doc.getType())== 3 || this.getDocumentTypeId(doc.getType()) == 4) systemGeneratedDocType=true;
	  }
	  }
	  return systemGeneratedDocType;
  }
}
		

