/**
 * Created on 4:44:56 PM Jan 11, 2005
 * Project: UI
 */
package gov.va.med.esr.ui.comms.action;

// Java classes
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

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.person.Person;
import gov.va.med.esr.service.external.HandBookInfo;
import gov.va.med.esr.ui.ApplicationConstants;
import gov.va.med.esr.ui.common.action.DownloadAction;
import gov.va.med.fw.service.ServiceConfigurationException;
import gov.va.med.fw.service.ServiceException;

public class HandbookDisplayAction extends DownloadAction {
	protected transient Log logger = LogFactory.getLog(getClass());
	public HandbookDisplayAction() {
		super();
	}

	protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		File file;

		if (mapping.getParameter().equalsIgnoreCase("handbook")) {			
			file = new File(displayHandbook(request));
		} else {			
			file = new File(displayBenefitGlance(request));
		}
		
		if(!file.exists()) {
			logger.error(file.getAbsoluteFile() + " file does not exist");
			throw new HandbookNotAvailableException();
		}
		
		String contentType = "application/pdf";//default
		if(file.getName()!= null && file.getName().endsWith("xml")){
			try{
				 ByteArrayInputStream bais = getHandBookService().convertXmlHandBookToPDF(file);
				 return new ByteStreamInfo(contentType, bais);				 
			} catch (ServiceException se) {
				logger.error("ERROR in converting XML handbook into PDF handbook: ", se);
				throw new HandbookNotAvailableException();
			}
		}
		
		return new FileStreamInfo(contentType, file);
	}

	public String displayBenefitGlance(HttpServletRequest request)
			throws Exception {
		
		//handle the query parameters from overview page
		String fileId= request.getParameter("fileId");

		if (fileId != null && fileId.length() > 0 )
		{
			BigDecimal id = new BigDecimal(fileId);
			FileInfo fileInfo = this.getHandBookService().getFileInfoById(id);
			getHandBookService().recordDocumentAccess(id);
			
			return getHandBookService().getVBRFileLocation(fileInfo.getDirectory()) + fileInfo.getName();
		}
		
		List handBookList = new ArrayList();
		Person person = getSelectedPerson(request);
		List hbResult = getHandBookService().getHandbookInformation(
				person.getIdentityTraits().getVpid().getVPID());
		
		// 3.6 CR 10227
		// this is where we get the correct version off the list (current or historical)
		String versionStr= request.getParameter("ver");
		int version = 0;
		if (versionStr != null && !versionStr.equals("")) {
			try {
				version = Integer.valueOf(versionStr);
			} catch (Exception ex) {
				// ignore for now
			}
		}
		
		buildHBVersion(hbResult, "Benefits Profile", handBookList, version);
		HandBookInfo benefitsProfile = (HandBookInfo) handBookList.get(0);
		String fileName = benefitsProfile.getPhysicalLocation()+ benefitsProfile.getName();

		return fileName;

	}

	public String displayHandbook(HttpServletRequest request) throws Exception {
		
		//handle the query parameters from overview page
		String fileId= request.getParameter("fileId");

		if (fileId != null && fileId.length() > 0 )
		{
			BigDecimal id = new BigDecimal(fileId);
			FileInfo fileInfo = this.getHandBookService().getFileInfoById(id);
			getHandBookService().recordDocumentAccess(id);
			
			return getHandBookService().getVBRFileLocation(fileInfo.getDirectory()) + fileInfo.getName();
		}
		
		List handBookList = new ArrayList();
		Person person = getSelectedPerson(request);
		List hbResult = getHandBookService().getHandbookInformation(
				person.getIdentityTraits().getVpid().getVPID());
		
		// 3.6 CR 10227
		// this is where we get the correct version off the list (current or historical)
		String versionStr= request.getParameter("ver");
		int version = 0;
		if (versionStr != null && !versionStr.equals("")) {
			try {
				version = Integer.valueOf(versionStr);
			} catch (Exception ex) {
				// ignore for now
			}
		}
		
		buildHBVersion(hbResult, "Handbook", handBookList, version);
		HandBookInfo handBook = (HandBookInfo) handBookList.get(0);
		String fileName = handBook.getPhysicalLocation() + handBook.getName();

		return fileName;
	}

	// 3.6 CR 10227
	private List buildHBVersion(List results, String request, List handBookList, int version) throws Exception {
		DocumentReceipt docReceipt = null;
		if (version == 0) {
			// no version specified - get the latest one
			docReceipt = (DocumentReceipt) results.get(0);
		} else {
			// we need to get a specific version of the file.  The ReceiptString will be the version
			// we are looking for
			boolean found = false;
			Iterator iter = results.iterator();
			while (iter.hasNext() && !found) {
				docReceipt = (DocumentReceipt) iter.next();
				int receiptStr = 0;
				try {
					receiptStr = Integer.valueOf(docReceipt.getReceiptString());
				} catch (Exception ex) {
					// ignore for now
				}
				if (receiptStr == version) {
					found = true;
				}
			}
		}

		buildDocument(docReceipt, request, handBookList);
		return handBookList;

	}

	private List buildDocument(DocumentReceipt docReceipt, String request,
			List handBookList)  throws Exception{
		Set Documents = docReceipt.getDocuments();
		for (Iterator iter = Documents.iterator(); iter.hasNext();) {
			Document doc = (Document) iter.next();
			if (doc.getDocumentType().getName() != null &&
					doc.getDocumentType().getName().contains(request)) {
				HandBookInfo hbi = new HandBookInfo();
				hbi.setDocType(doc.getDocumentType().getName());
				hbi.setGeneratedDate(doc.getCreationDate());
				hbi.setName(doc.getFileInfo().getName());
				
				getHandBookService().recordDocumentAccess((BigDecimal)doc.getFileInfo().getEntityKey().getKeyValue());
				//hbi.setPhysicalLocation(doc.getFileInfo().getDirectory()
				//		.getMountPoint().getName()
				//		+ doc.getFileInfo().getDirectory().getName());
				
				hbi.setPhysicalLocation(
				getHandBookService().getVBRFileLocation(doc.getFileInfo().getDirectory()));
				
				hbi.setReleaseControlNumber(docReceipt.getReleaseControlNumber());
				hbi.setVersion(docReceipt.getVersionNumber());
				handBookList.add(hbi);
			}
		}
		return handBookList;
	}

	/**
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() {
		// Check for required components here
	}

	protected Map getKeyMethodMap() {
		Map map = new HashMap();
		// Handbook project
		map.put("title.benefitGlance", "displayBenefitGlance");
		map.put("title.handbook", "displayHandbook");
		return map;
	}

	protected CommsLogForm getCommsLogForm(ActionForm form)
			throws ServiceConfigurationException {
		CommsLogForm specificForm = (form instanceof CommsLogForm) ? (CommsLogForm) form
				: null;
		if (specificForm == null) {
			throw new ServiceConfigurationException(
					"CommsLogForm not properly configured.");
		}
		return specificForm;
	}
}