package gov.va.med.esr.ui.ee.action;

// Java Classes
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import gov.va.med.fw.security.Principal;
import gov.va.med.fw.service.ServiceConfigurationException;
import gov.va.med.fw.util.StringUtils;

import gov.va.med.esr.common.infra.TriState;
import gov.va.med.esr.common.model.ee.PurpleHeart;
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.DecorationStatus;
import gov.va.med.esr.common.model.lookup.EligibilityDocType;
import gov.va.med.esr.common.model.person.Person;

import gov.va.med.esr.ui.conversion.UIConversionService;
import gov.va.med.esr.ui.util.ConvertUtils;
import gov.va.med.esr.ui.util.SessionManager;
import gov.va.med.esr.service.EligibilityEnrollmentService;

/**
 * Handles actions for the eligibility edit screen.
 *
 * @author Bin Chen
 * @author Andrew Pach
 * @version 3.0
 */
public class EligibilityEditAction extends EligibilityAction {
    // The number of additional empty rated disabilities to add to the screen
    // when the user makes the request
    private static final int ADD_NEW_DISABILITIES_COUNT = 8;

    public static final String NO_VET_IND_YES_WITH_INELIGIBILE_DATE_MESSAGE_KEY = "error.noVetIndYesWithIneligibleDate";

    public void afterPropertiesSet() throws Exception {
        if (getPersonService() == null || getLookupService() == null
                || getEnrollmentService() == null) {
            throw new ServiceConfigurationException(
                    "Missing required service(s)(searchService/lookupService/enrollmentCalculateService");
        }
    }

    /**
     * Preview eligibility screen
     *
     * @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 cancel(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // Remove the updated person from session
        setUpdatedPerson(request, null);

        return mapping.findForward("cancel");
    }

    public ActionForward acceptChanges(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(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(eligibilityForm, updatedPersonClone);
        conversionService.merge((Person)getSelectedPerson(request),
                updatedPersonClone);
        
        // Perform the database update
        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);
        if (!isAddAPerson) {
	        VOAAttahmentEditActionForm vOAAttahmentEditActionForm = null;

	        BigDecimal key = new BigDecimal(updatedPersonClone.getPersonEntityKey()
	                .getKeyValueAsString());
	        List voaAttachments = this.getVoaApplicationService()
	                .findVoaAttachmentByPersonId(key.abs());
	        if(voaAttachments != null && !(voaAttachments.isEmpty())){

	        Iterator itrVoaAttachment = voaAttachments.iterator();

	        while (itrVoaAttachment.hasNext()) {
	            VoaFileAttachment voaFileAttachment = (VoaFileAttachment) itrVoaAttachment
	                    .next();
	            List voaFormAttachements = eligibilityForm.getVoaAttachments();
	            for (int i = 0; i < voaFormAttachements.size(); i++) {
	                vOAAttahmentEditActionForm = (VOAAttahmentEditActionForm) voaFormAttachements
	                        .get(i);
	                if (voaFileAttachment.getEntityKey().getKeyValueAsString()
	                        .equals(vOAAttahmentEditActionForm.getParentKey())) {

	                    Set voaAttachmentDetails = voaFileAttachment
	                            .getAttachmentDetailLst();
	                    Iterator iterator = voaAttachmentDetails.iterator();
	                    while (iterator.hasNext()) {
	                        VoaFileAttachmentDetail voaFileAttachmentDetail = (VoaFileAttachmentDetail) iterator
	                                .next();
	                        if (voaFileAttachmentDetail.getVoaFileAttachment()
	                                .getEntityKey().getKeyValueAsString().equals(
	                                        vOAAttahmentEditActionForm
	                                                .getParentKey())) {
	                            voaFileAttachmentDetail
	                                    .setEligibilityDocType((EligibilityDocType) getLookupService()
	                                            .getByCode(
	                                                    EligibilityDocType.class,
	                                                    vOAAttahmentEditActionForm
	                                                            .getVoaAttachmentDocTypeCode()));

	                        }

	                    }

	                }

	            }

	            this.getVoaApplicationService().updateAttachmentAttributes(
                    voaFileAttachment);
	        }
        }
        }

        // List voaAttachments =
        // (List)request.getSession().getAttribute("VOA_ATTACMENTLIST");

        // Go to the service period screen if required
        if (updatedPersonClone != null && getEnrollmentService().isServicePeriodNeeded(updatedPersonClone))
        {
            setUpdatedPerson(request, updatedPersonClone);
            return mapping.findForward("servicePeriod");
        }

        
        // Perform the database update
        try{
        if (!isAddAPerson)
        	updatedPersonClone = getEnrollmentService().updateEligibilityData(updatedPersonClone);
        }catch(Exception e){
        	e.printStackTrace(System.out);
        }
        

        // The change was successful so update the selected person and removed
        // the updated person
        if (updatedPersonClone != null)
        {
            updateSelectedPerson(request, updatedPersonClone);
            setUpdatedPerson(request, null);
        }

        return mapping.findForward("acceptChanges");
    }

    /**
     * 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
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(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(eligibilityForm, 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 = eligibilityForm
                    .getVoaAttachments();
            Set newAttachments = new HashSet();
            for (int i = 0; i < voaFormAttachementsInComming.size(); i++) {
                vOAAttahmentEditActionFormInComming = (VOAAttahmentEditActionForm) voaFormAttachementsInComming
                        .get(i);

                if(vOAAttahmentEditActionFormInComming.getVoaAttachmentDocTypeCode().equals("99")){
                    continue;
                }
                if (voaFileAttachmentOnFile.getEntityKey()
                        .getKeyValueAsString().equals(
                                vOAAttahmentEditActionFormInComming
                                        .getParentKey())) {
                    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);
                        }
                    }
                    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);
                    }
                }
                vOAAttahmentEditActionFormInComming = null;
            }//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("updateVOAAttachments");
    }


    public ActionForward addVoaAttachmentsDocTypes(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);
        String rowID = eligibilityForm.getActiveVOARowID();
        int rowNumber = 0;
        if(rowID != null && !rowID.equals("")){
            rowNumber = Integer.parseInt(rowID);
        }

        //eligibilityForm.getVoaAttachment(request.)
        VOAAttahmentEditActionForm vOAAttahmentEditActionFormInComming = null;
        VOAAttahmentEditActionForm vOAAttahmentEditActionFormNew = new VOAAttahmentEditActionForm();
        List voaFormAttachementsInComming = eligibilityForm.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);
        eligibilityForm.setVoaAttachments(voaFormAttachementsInComming);
        return mapping.findForward("success");
    }




    public ActionForward preview(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(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(eligibilityForm, updatedPersonClone);
        conversionService.merge((Person)getSelectedPerson(request), updatedPersonClone);

        // CCR12877 -- when reviewing for impact, do not trigger HBP rules
        updatedPersonClone = getEnrollmentService().assessEEImpact(updatedPersonClone, true, true, false);

        // We were able to successfully assess the preview, but no changes were written to the database yet.
        // So just update the "updated person" in session in case the user "accepts" the changes on the next screen.
        if (updatedPersonClone != null)
        {
            setUpdatedPerson(request, updatedPersonClone);
        }

        return mapping.findForward("eligibilityEditReview");
    }

    /**
     * Displays the edit eligibility screen initially.
     *
     * @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 edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        eligibilityForm.setAddAPerson(SessionManager.isAddAPerson(request));

        // Make a clone of the selected person and place it in session as the "updated person".
        // This is needed because of the various operations the user can make on the edit screen
        // including previewing the changes.
        Person person = (Person)getSelectedPerson(request).clone();
        setUpdatedPerson(request, person);

        // Prepare the person's data onto the form
        UIConversionService uiConversionService = (UIConversionService)conversionService;
        uiConversionService.convert(person, eligibilityForm);
         /////////////////////////////////CLV//////////////////////////////////////////////////
		eligibilityForm.setCampLejeuneDisabled(!getMilitaryInfoService().calculateCLVeligibilitybyMSE(person));
		////////////////////////////OR///////////////////////////////////////////////////////////
		SessionManager.setAttribute(request,"clveligible",getMilitaryInfoService().calculateCLVeligibilitybyMSE(person));
		//IS_CAMP_LEJEUNE_ELIGIBLE					= "clveligible"; //CLV//
		////////////////////////////////CLV///////////////////////////////////////////////////


        populateWireFrame(eligibilityForm, person, request);
        return mapping.findForward("success");
    }

    /* A method used to populate wire frame */
    /** populateWireFrame method is used to populate wireframe with the data */
    private void populateWireFrame(EligibilityEditActionForm eligibilityForm,
            Person person, HttpServletRequest request) throws Exception {

        boolean isAddAPerson = false;
        isAddAPerson = SessionManager.isAddAPerson(request);

        if (!isAddAPerson) {
	        BigDecimal key = new BigDecimal(person.getPersonEntityKey()
	                .getKeyValueAsString());

	        List 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());
	                    vOAAttahmentEditActionForm.setParent(true);

	                    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++;
	                    }
	                    eligibilityForm.setVoaAttachments(voaAttachments);
                }
	        } else {
	        	eligibilityForm.setVoaAttachments(new ArrayList());
	        }
        }
    }


    public ActionForward openDocument(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        VOAAttahmentEditActionForm attachmentForm = null;
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);
        List attachments = eligibilityForm.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");
    }



    public ActionForward addPow(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        // Update the POW information on the form
        eligibilityForm.setPowInd("Yes");
        eligibilityForm.addNewPow();
        eligibilityForm.setAddPOWSource(eligibilityForm.getPowIdList().size()-1);

        return mapping.findForward("addPow");
    }

    public ActionForward setNoPow(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        // Remove the POW information from the form
        eligibilityForm.setPowInd("No");
        eligibilityForm.initPow();

        return mapping.findForward("addPow");
    }

    /**
     * Req 5919, Reset some veteran fields when user changes the veteran indicator to No.
     *
     * @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 setVeteranIndNo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        // Set the veteran indicator to No
        eligibilityForm.setVeteranIndicator("n");

        if (eligibilityForm.getPowInd() != null && eligibilityForm.getPowInd().equals("Yes"))
        {
            eligibilityForm.setPowInd("No");
        }
        eligibilityForm.initPow();
        eligibilityForm.removeAllDisability();

        // 2240[UC17.14.18] Manage Eligibility and Enrollment Decision Table
        eligibilityForm.setServiceConnected(null);
        if (eligibilityForm.getUnemployable().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setUnemployable(ConvertUtils.NO_VALUE);
        }
        if (eligibilityForm.getPermanentTotal().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setPermanentTotal(ConvertUtils.NO_VALUE);
        }
        eligibilityForm.setPermanentTotalEffDate(null);
        if (eligibilityForm.getIsReceivingCompensation().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setIsReceivingCompensation(ConvertUtils.NO_VALUE);
        }
        if (eligibilityForm.getAidAttendance().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setAidAttendance(ConvertUtils.NO_VALUE);
        }
        if (eligibilityForm.getHousebound().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setHousebound(ConvertUtils.NO_VALUE);
        }
        if (eligibilityForm.getVaPension().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setVaPension(ConvertUtils.NO_VALUE);
        }
        eligibilityForm.setTotalCheckAmount(null);
        eligibilityForm.setTotalMonthlyCheckAmount(null);
        if (eligibilityForm.getEligibleForMedicaid().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setEligibleForMedicaid(ConvertUtils.NO_VALUE);
            eligibilityForm.setMedicaidUpdatedDate(eligibilityForm.getTodayDate());
        }
        if (eligibilityForm.getDisabilityRetirementIndicator().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setDisabilityRetirementIndicator(ConvertUtils.NO_VALUE);
        }
        if (eligibilityForm.getDischargeDueDisability().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setDischargeDueDisability(ConvertUtils.NO_VALUE);
        }
        eligibilityForm.setAgentOrangeLocation(null);
        eligibilityForm.setRadiationExposureMethod(null);

        if (eligibilityForm.getEnvironmentalContaminationExposure().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setEnvironmentalContaminationExposure(ConvertUtils.NO_VALUE);
        }
         ///////////////////////////CLV//////////////////////////////////////////
		if (eligibilityForm.getCampLejeuneInd().equals(ConvertUtils.YES_VALUE))
		{
			eligibilityForm.setCampLejeuneInd(ConvertUtils.NO_VALUE);
		}
		/////////////////////////////CLV/////////////////////////////////////////

        //set purple heart status
        PurpleHeart ph = getSelectedPerson(request).getPurpleHeart();
        if (ph == null || ph.getStatus() == null){
        	eligibilityForm.setPhStatus(null);
        }
        else if (ph.getPhIndicator() != null && ph.getPhIndicator().booleanValue()){
        	// set the status to rejected
        	eligibilityForm.setPhStatus(DecorationStatus.CODE_REJECTED.getCode());
        }
        else {
        	eligibilityForm.setPhStatus(ph.getStatus().getCode());
        }
        return mapping.findForward("addDisability");
    }

    /**
     * Reverse 5919, setVeteranIndNo
     *
     * @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 setVeteranIndYes(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        // Set the veteran indicator to Yes
        eligibilityForm.setVeteranIndicator("y");

        //Reset Purple Heart Status
        PurpleHeart ph = getSelectedPerson(request).getPurpleHeart();
        if (ph == null || ph.getStatus() == null) {
            eligibilityForm.setPhStatus(null);
        }
        else {
            eligibilityForm.setPhStatus(ph.getStatus().getCode());
        }

        return mapping.findForward("addDisability");
    }

    /**
     * Add additional rated disabilities.
     *
     * @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 addRatedDisability(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        // Add additional empty disabilities
        for (int i = 0; i < ADD_NEW_DISABILITIES_COUNT; i++)
        {
            eligibilityForm.addNewDisability(i);
        }

        eligibilityForm.setAddedRatedDisability("y");


        return mapping.findForward("addDisability");
    }

    public ActionForward removeAllRatedDisability(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the specific form
        EligibilityEditActionForm eligibilityForm = getEligibilityForm(form);

        eligibilityForm.removeAllDisability();
        eligibilityForm.setFocusButton("removeAllRatedDisability");
        //2240[UC17.14.18] Manage Eligibility and Enrollment Decision Table
        eligibilityForm.setServiceConnected(null);
        eligibilityForm.setUnemployable(ConvertUtils.NO_VALUE);
        eligibilityForm.setPermanentTotal(ConvertUtils.NO_VALUE);
        eligibilityForm.setPermanentTotalEffDate(null);
        eligibilityForm.setIsReceivingCompensation(ConvertUtils.NO_VALUE);
        if (!eligibilityForm.getAidAttendance().equals(ConvertUtils.YES_VALUE)
            && !eligibilityForm.getHousebound().equals(ConvertUtils.YES_VALUE)
            && !eligibilityForm.getVaPension().equals(ConvertUtils.YES_VALUE))
        {
            eligibilityForm.setTotalCheckAmount(null);
            eligibilityForm.setTotalMonthlyCheckAmount(null);
        }

        return mapping.findForward("addDisability");
    }




    /**
     * Gets the screen specific form.
     * @param form The generic form.
     * @return the screen specific form
     */
    protected EligibilityEditActionForm getEligibilityForm(ActionForm form)
    {
        // Get the specific form
        return (form instanceof EligibilityEditActionForm) ? (EligibilityEditActionForm) form : null;
    }

    /**
     * Gets the key method map.
     *
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     * @return the key method map
     */
    protected Map getKeyMethodMap()
    {
        Map map = new HashMap();
        map.put("button.addRatedDisability", "addRatedDisability");
        map.put("button.removeAllRatedDisability", "removeAllRatedDisability");
        map.put("button.reviewImpact", "preview");
        map.put("button.acceptChanges", "acceptChanges");
        map.put("button.cancel", "cancel");
        map.put("eligibilityView.link.edit", "edit");
        map.put("button.discardChanges", "edit");
        map.put("button.addPow", "addPow");
        map.put("button.setNoPow", "setNoPow");
        map.put("button.setVeteranIndNo", "setVeteranIndNo");
        map.put("button.setVeteranIndYes", "setVeteranIndYes");
        map.put("link.openDocument", "openDocument");
        map.put("button.ADD_VoaDocTypes", "addVoaAttachmentsDocTypes");
        map.put("button.UPDATE_Attributes", "updateVoaAttachments");

        return map;
    }

//    protected String getNoseThroatRadium(Person person) {
//    	TriState tristate = person.getNoseThroatRadium().getReceivingTreatment();
//    	Boolean b = null;
//    	if (tristate.equals(TriState.TRUE)) b = new Boolean(true);
//    	if (tristate.equals(TriState.FALSE)) b = new Boolean(false);
//
//    	return ConvertUtils.convertYesNoNoData(b);
//    }
//
//    protected void setNoseThroatRadium(Person person, String value) {
//    	Boolean b = ConvertUtils.convertBoolean(value);
//    	TriState triState;
//    	if (b == null) {
//    		triState = TriState.UNKNOWN;
//    	} else if (b.booleanValue()) {
//    		triState = TriState.TRUE;
//    	} else {
//    		triState = TriState.FALSE;
//    	}
//
//    	person.getNoseThroatRadium().setReceivingTreatment(triState);
//    }
 }