/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.ui.ee.action;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
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.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import gov.va.med.fw.ui.struts.AbstractForm;
import gov.va.med.fw.util.StringUtils;

import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.ee.VoaFileAttachment;
import gov.va.med.esr.common.model.ee.VoaFileAttachmentDetail;
import gov.va.med.esr.common.model.lookup.Capability;
import gov.va.med.esr.common.model.lookup.EligibilityDocType;

import gov.va.med.esr.ui.common.action.PersonAbstractAction;
import gov.va.med.esr.ui.conversion.UIConversionService;
import gov.va.med.esr.ui.util.SessionManager;

public class PurpleHeartAction extends PersonAbstractAction {

    public static final String FWD_EDIT = "edit";
        
    public PurpleHeartAction() {
        super();
    }
    
    public void afterPropertiesSet() throws Exception {
    }

    public ActionForward display(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        //if the user has view only permissions forward to view page
        //if the user has permission to update forward to edit
        Person person = (Person) getSelectedPerson(request).clone();
        setUpdatedPerson(request, person);
        conversionService.convert(person,form);
        //if the user has PH processing Capability set LAS to the current logged in User
        if (isPermissionGranted(Capability.EDIT_PURPLE_HEART_INFO.getCode())) {
        	((PurpleHeartForm)form).setNewAssignedContactUser(getLoggedInUser().getName());
        }
        ((PurpleHeartForm)form).setReturnLink(request.getParameter(RETURN_LINK));
        populateWireFrame(form, person, request);     
        return mapping.findForward(FWD_EDIT);
    }

    public ActionForward update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Person person = getSelectedPerson(request);
        Person updatedPerson = (Person)person.clone();
        conversionService.convert(form,updatedPerson);
        
        // Create some action forwards
        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);

        if (! isAddAPerson){
        	updatedPerson = getPurpleHeartService().updatePurpleHeart(updatedPerson);
        }
        updateSelectedPerson(request,updatedPerson); 
        
        //get service and update person
        return mapping.findForward(FWD_DISPLAY_UPDATE_MSG);
    }
    
    public ActionForward cancel(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {    
        //get the return link
        String returnLink = ((PurpleHeartForm)form).getReturnLink();
        return StringUtils.isEmpty(returnLink) ? mapping.findForward(FWD_CANCEL):
            mapping.findForward(returnLink);        
    }
    
    /** populateWireFrame method is used to populate wireframe with the data */

    private void populateWireFrame(ActionForm form,
            Person person, HttpServletRequest request) throws Exception {
        
        PurpleHeartForm purpleHeartForm =(PurpleHeartForm)form;
        
        List eeService = null;
       
        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        if (!isAddAPerson) {

	        BigDecimal key = new BigDecimal(person.getPersonEntityKey()
	                .getKeyValueAsString());
	
	        eeService = this.getVoaApplicationService()
	                .findVoaAttachmentByPersonId(key.abs());
        }
        
        if(eeService != null && !(eeService.isEmpty())){
                Iterator itrVoaAttachment = eeService.iterator();
                VoaFileAttachment voaFileAttachment = null;
                List voaAttachments = new ArrayList();
        
                while (itrVoaAttachment.hasNext()) {
                    VOAAttahmentEditActionForm vOAAttahmentEditActionForm = new VOAAttahmentEditActionForm();
                    voaFileAttachment = (VoaFileAttachment) itrVoaAttachment.next();
        
                    vOAAttahmentEditActionForm
                            .setVoaAttachmentFileName(voaFileAttachment.getFileName());
                    String fileType[] = voaFileAttachment.getFileMimeType().split("/");
                    if(fileType != null && fileType.length >1){
                        vOAAttahmentEditActionForm
                        .setVoaAttachmentFileType(fileType[1]);
                    }
                    else if(fileType != null && fileType.length > 0){
                       vOAAttahmentEditActionForm
                            .setVoaAttachmentFileType(voaFileAttachment.getFileMimeType());
                    }
                    vOAAttahmentEditActionForm.setContentType(voaFileAttachment.getFileMimeType());
                    vOAAttahmentEditActionForm
                            .setVoaAttachmentUpdated(voaFileAttachment
                                    .getAttachmentReviewDate());
                    vOAAttahmentEditActionForm
                            .setVoaAttachmentUpdatedBy(voaFileAttachment
                                    .getAttachmentReviewUserName());
                    
                    vOAAttahmentEditActionForm
                    .setVoaAttachmentFileBuffer(voaFileAttachment
                            .getAttachmentImage()!=null ? voaFileAttachment
                                    .getAttachmentImage().getFileImage() : null);

                    
                    vOAAttahmentEditActionForm
                    .setParentKey(voaFileAttachment
                            .getEntityKey()
                            .getKeyValueAsString());
                    if(voaFileAttachment.getAttchmentAcceptableInd() == Boolean.TRUE){
                        vOAAttahmentEditActionForm.setVoaAttachmentAccept("on");
                    }
                    voaAttachments.add(vOAAttahmentEditActionForm);
        
                    Set docTypesSet = voaFileAttachment.getAttachmentDetailLst();
        
                    Iterator itr = docTypesSet.iterator();
        
                    int docTypeCounter = 0;
        
                    while (itr.hasNext()) {
                        VoaFileAttachmentDetail voaFileAttachmentDetail = null;
                        voaFileAttachmentDetail = (VoaFileAttachmentDetail) itr.next();
        
                        if (docTypeCounter == 0) {
                            vOAAttahmentEditActionForm
                                    .setVoaAttachmentDocType(voaFileAttachmentDetail
                                            .getEligibilityDocType().getName());
                            vOAAttahmentEditActionForm
                                    .setVoaAttachmentDocTypeCode(voaFileAttachmentDetail
                                            .getEligibilityDocType().getCode());
                            vOAAttahmentEditActionForm
                                    .setParentKey(voaFileAttachmentDetail
                                            .getVoaFileAttachment().getEntityKey()
                                            .getKeyValueAsString());
                            vOAAttahmentEditActionForm.setVoaAttachmentUpdated(voaFileAttachmentDetail.getModifiedOn());
                            vOAAttahmentEditActionForm.setVoaAttachmentUpdatedBy(voaFileAttachmentDetail.getModifiedBy().getName());
                            vOAAttahmentEditActionForm.setParent(true);
                        }
        
                        else if (docTypeCounter != 0) {
                            VOAAttahmentEditActionForm newVOAAttahmentEditActionForm = new VOAAttahmentEditActionForm();
                            newVOAAttahmentEditActionForm
                                    .setVoaAttachmentDocType(voaFileAttachmentDetail
                                            .getEligibilityDocType().getName());
                            newVOAAttahmentEditActionForm
                                    .setVoaAttachmentDocTypeCode(voaFileAttachmentDetail
                                            .getEligibilityDocType().getCode());
                            newVOAAttahmentEditActionForm
                                    .setParentKey(voaFileAttachmentDetail
                                            .getVoaFileAttachment().getEntityKey()
                                            .getKeyValueAsString());
                            newVOAAttahmentEditActionForm.setVoaAttachmentUpdated(voaFileAttachmentDetail.getModifiedOn());
                            newVOAAttahmentEditActionForm.setVoaAttachmentUpdatedBy(voaFileAttachmentDetail.getModifiedBy().getName());
                            newVOAAttahmentEditActionForm.setParent(false);
                            voaAttachments.add(newVOAAttahmentEditActionForm);
                        }
                        docTypeCounter++;
                    }
                    purpleHeartForm.setVoaAttachments(voaAttachments);
                }
        } else {
        	purpleHeartForm.setVoaAttachments(new ArrayList());
        }
    }
    
    public ActionForward addVoaAttachmentsDocTypes(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        PurpleHeartForm purpleHeartForm = getPurpleHeartForm(form);
        int rowNumber = 0;
        if(purpleHeartForm.getActiveVOARowID() != null && !purpleHeartForm.getActiveVOARowID().equals("") ){
            rowNumber =  Integer.parseInt(purpleHeartForm.getActiveVOARowID());
        }

        VOAAttahmentEditActionForm vOAAttahmentEditActionFormInComming = null;
        VOAAttahmentEditActionForm vOAAttahmentEditActionFormNew = new VOAAttahmentEditActionForm();
        List voaFormAttachementsInComming = purpleHeartForm.getVoaAttachments();
        vOAAttahmentEditActionFormInComming = (VOAAttahmentEditActionForm) voaFormAttachementsInComming.get(rowNumber);
        vOAAttahmentEditActionFormNew.setVoaAttachmentFileName(vOAAttahmentEditActionFormInComming.getVoaAttachmentFileName());

        vOAAttahmentEditActionFormNew
                .setVoaAttachmentFileType(vOAAttahmentEditActionFormInComming
                        .getVoaAttachmentFileType());
        vOAAttahmentEditActionFormNew
                .setVoaAttachmentUpdated(vOAAttahmentEditActionFormInComming
                        .getVoaAttachmentUpdated());
        vOAAttahmentEditActionFormNew
                .setVoaAttachmentUpdatedBy(vOAAttahmentEditActionFormInComming
                        .getVoaAttachmentUpdatedBy());
        vOAAttahmentEditActionFormNew
                .setVoaAttachmentFileBuffer(vOAAttahmentEditActionFormInComming
                        .getVoaAttachmentFileBuffer());
        vOAAttahmentEditActionFormNew.setParentKey(vOAAttahmentEditActionFormInComming
                .getParentKey());

        voaFormAttachementsInComming.add(rowNumber + 1, vOAAttahmentEditActionFormNew);
        purpleHeartForm.setVoaAttachments(voaFormAttachementsInComming);
        return mapping.findForward("addVoaAttachmentsDocTypes");
    }
    
    /**
     * Gets the screen specific form.
     * @param form The generic form.
     * @return the screen specific form
     */
    protected PurpleHeartForm getPurpleHeartForm(ActionForm form)
    {
        // Get the specific form
        return (form instanceof PurpleHeartForm) ? (PurpleHeartForm) form : null;
    }    
    
    /**
     * update VOA Attachments.
     *
     * @param mapping
     *            An action mapping
     * @param form
     *            A form bean
     * @param request
     *            A http request from an search.jsp page
     * @param response
     *            A http response to stream data to a next page
     *
     * @return An action forward class encapsulating information about a next
     *         page
     * @throws Exception
     *             Thrown if failed to process
     */

    
    public ActionForward updateVoaAttachments(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // Get the specific form
        PurpleHeartForm purpleHeartForm = getPurpleHeartForm(form);

        // Get a clone of the updated person
        Person updatedPersonClone = (Person) getUpdatedPerson(request).clone();

        // Modify the cloned updated person with the latest updates
        conversionService.convert(purpleHeartForm, updatedPersonClone);
        conversionService.merge((Person) getSelectedPerson(request),
                updatedPersonClone);

        

        VOAAttahmentEditActionForm vOAAttahmentEditActionFormInComming = null;

        BigDecimal key = new BigDecimal(updatedPersonClone.getPersonEntityKey()
                .getKeyValueAsString());
        List voaAttachmentsOnFile = this.getVoaApplicationService()
                .findVoaAttachmentByPersonId(key.abs());
        if(voaAttachmentsOnFile != null && !(voaAttachmentsOnFile.isEmpty())){
            Iterator itrVoaAttachmentOnFile = voaAttachmentsOnFile.iterator();
    
            while (itrVoaAttachmentOnFile.hasNext()) {
    
                VoaFileAttachment voaFileAttachmentOnFile = (VoaFileAttachment) itrVoaAttachmentOnFile
                        .next();
                List voaFormAttachementsInComming = purpleHeartForm
                        .getVoaAttachments();
                Set newAttachments = new HashSet();
                for (int i = 0; i < voaFormAttachementsInComming.size(); i++) {
                    vOAAttahmentEditActionFormInComming = (VOAAttahmentEditActionForm) voaFormAttachementsInComming
                            .get(i);
                    if(vOAAttahmentEditActionFormInComming.isParent() && vOAAttahmentEditActionFormInComming.getVoaAttachmentFileName()!= null && vOAAttahmentEditActionFormInComming.getVoaAttachmentFileName().equals(voaFileAttachmentOnFile.getFileName())){
                        String value = (String)request.getParameter("voaAttachment["+ i +"].voaAttachmentAccept");
                        if(value != null){
                            voaFileAttachmentOnFile.setAttchmentAcceptableInd(new Boolean(true));
                            vOAAttahmentEditActionFormInComming.setVoaAttachmentAccept("on");
                        }else{
                            voaFileAttachmentOnFile.setAttchmentAcceptableInd(new Boolean(false));
                            vOAAttahmentEditActionFormInComming.setVoaAttachmentAccept(null);
                        }
                    }
                    if(vOAAttahmentEditActionFormInComming.getVoaAttachmentDocTypeCode().equals("99")){
                        continue;
                    }
                    if (voaFileAttachmentOnFile.getEntityKey()
                            .getKeyValueAsString().equals(
                                    vOAAttahmentEditActionFormInComming
                                            .getParentKey())) {
    
                        Set voaAttachmentDetailsOnFile = voaFileAttachmentOnFile
                                .getAttachmentDetailLst();
                        if (voaAttachmentDetailsOnFile.size() > 0) {
                            Iterator iterator = voaAttachmentDetailsOnFile
                                    .iterator();
                            boolean matchFound = false;
                            while (iterator.hasNext()) {
                                VoaFileAttachmentDetail voaFileAttachmentDetailOnFile = (VoaFileAttachmentDetail) iterator
                                        .next();
    
                                if (voaFileAttachmentDetailOnFile
                                        .getVoaFileAttachment().getEntityKey()
                                        .getKeyValueAsString().equals(
                                                vOAAttahmentEditActionFormInComming
                                                        .getParentKey())) {
    
                                    voaFileAttachmentDetailOnFile
                                            .setEligibilityDocType((EligibilityDocType) getLookupService()
                                                    .getByCode(
                                                            EligibilityDocType.class,
                                                            vOAAttahmentEditActionFormInComming
                                                                    .getVoaAttachmentDocTypeCode()));
                                    newAttachments
                                            .add(voaFileAttachmentDetailOnFile);
                                    voaAttachmentDetailsOnFile.remove(voaFileAttachmentDetailOnFile);
                                    matchFound = true;
                                    break;
                                }
                            }
    
                            if(!matchFound){
                                VoaFileAttachmentDetail newDetail = new VoaFileAttachmentDetail();
                                newDetail
                                .setEligibilityDocType((EligibilityDocType) getLookupService()
                                        .getByCode(
                                                EligibilityDocType.class,
                                                vOAAttahmentEditActionFormInComming
                                                        .getVoaAttachmentDocTypeCode()));
                                
                                newDetail.setVoaFileAttachment(voaFileAttachmentOnFile);
                                newAttachments.add(newDetail);
                            }
                        } else {
                            VoaFileAttachmentDetail detail1 = new VoaFileAttachmentDetail();
                            detail1
                                    .setEligibilityDocType((EligibilityDocType) getLookupService()
                                            .getByCode(
                                                    EligibilityDocType.class,
                                                    vOAAttahmentEditActionFormInComming
                                                            .getVoaAttachmentDocTypeCode()));
                            
                            detail1.setVoaFileAttachment(voaFileAttachmentOnFile);
                            newAttachments.add(detail1);
                        }
                    }
                }//end for
                voaFileAttachmentOnFile.removeAllVoaAttachmentDetails();
                Iterator itr = newAttachments.iterator();
                while(itr.hasNext()){
                    VoaFileAttachmentDetail attachmentDetails = (VoaFileAttachmentDetail)itr.next();
                    voaFileAttachmentOnFile.addVoaAttachmentDetail(attachmentDetails);
                }
                this.getVoaApplicationService().updateAttachmentAttributes(voaFileAttachmentOnFile);
            }//end while
        }
        return mapping.findForward("updateVOAAttachmentsPurpleHeart");
    }
    
    public ActionForward openDocument(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        VOAAttahmentEditActionForm attachmentForm = null;
        PurpleHeartForm purpleHeartForm = getPurpleHeartForm(form);
        List attachments = purpleHeartForm.getVoaAttachments();

        Iterator itr = attachments.iterator();
        // System.out.println("Here is the method call : " +
        String docName = request.getParameter("documentName");
        byte buffer[] = null;

        while (itr.hasNext()) {
            attachmentForm = (VOAAttahmentEditActionForm) itr.next();
           
            String fileName = attachmentForm.getVoaAttachmentFileName();
            
            if(docName.equals(fileName)){
                String fileType = attachmentForm.getVoaAttachmentFileType();
                buffer = attachmentForm.getVoaAttachmentFileBuffer();
                // response.setHeader("Cache-Control", "no-cache");
                response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
                response.setContentType(attachmentForm.getContentType());
                OutputStream outStream = null;
                try {
                    outStream = response.getOutputStream();
                    outStream.write(buffer);
                    outStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }                
            }
        }
        
        return mapping.findForward("displayDoc");
    }
    
    protected Map getKeyMethodMap()
    {
        Map map = new HashMap();
        map.put("button.display", "display");
        map.put("button.update", "update");
        map.put("button.cancel", "cancel");
        map.put("button.ADD_VoaDocTypes", "addVoaAttachmentsDocTypes");
        map.put("link.openDocument", "openDocument");
        map.put("button.UPDATE_Attributes", "updateVoaAttachments");
        return map;
    }        
}
