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

// Java classes
import java.util.List;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Library classes
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.commons.lang.Validate;
import net.mlw.vlh.ValueList;

// Framework classes
import gov.va.med.fw.ui.struts.ValueListActionUtils;

// ESR classes
import gov.va.med.esr.common.model.ee.ServiceConnectionAward;
import gov.va.med.esr.common.model.ee.SpecialFactor;
import gov.va.med.esr.common.model.comms.VCDeterminationHistoryForm;
import gov.va.med.esr.common.model.comms.GeocodeTransmit;
import gov.va.med.esr.common.model.comms.Waittime;
import gov.va.med.esr.common.model.ee.RatedDisability;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.service.VeteransChoiceInformationService;
import gov.va.med.esr.common.model.lookup.DiagnosticExtremity;
import gov.va.med.esr.common.model.lookup.PhoneType;
import gov.va.med.esr.common.model.party.Phone;
import gov.va.med.esr.ui.conversion.UIConversionService;

/**
 * Struts action to handle the eligibility view screen.
 */
public class EligibilityViewAction extends EligibilityAction
{
    public EligibilityViewAction()
    {
        super();
    }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet()
    {
        Validate.notNull(getPersonService(), "A person service is required.");
        Validate.notNull(getPersonHelperService(), "A person helper service is required.");
    }

    /**
     * Displays a search record
     *
     * @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 display(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        return redisplay(mapping, form, request, response);
    }

    public ActionForward redisplay(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        // Get the screen specific form
        EligibilityViewForm eligibilityForm = (form instanceof EligibilityViewForm) ? (EligibilityViewForm)form : null;

        // Get the currently selected person
        Person person = getSelectedPerson(request);

        // Set the person on the form
        if (eligibilityForm != null) {
        	eligibilityForm.setPerson(person);

	        // Convert the person data onto the form
	        UIConversionService uiConversionService = (UIConversionService)conversionService;
	        uiConversionService.convert(person, eligibilityForm);
        }

        // Set the rated disability data into a valuelist
        ValueList valueList = ValueListActionUtils.getValueList(form,
            request, "ratedDisabilitiesTableId", "ratedDisabilitiesAdapter", getRatedDisabilities(person));

        // Backup the ValueListInfo into session and store the resultant ValueList on the request
        ValueListActionUtils.setValueList(request, valueList, "vlhlist");

        return mapping.findForward("success");
    }

    /**
     * Get the list of rated disabilities
     * @param person The person
     * @return the rated disabilities
     */
    private List getRatedDisabilities(Person person)
    {
        ServiceConnectionAward scAward = person.getServiceConnectionAward();
        if ((scAward != null) && (scAward.getRatedDisabilities() != null) &&
            (scAward.getRatedDisabilities().size() > 0))
        {
            ArrayList results = new ArrayList();
            ArrayList disabilities = new ArrayList(scAward.getRatedDisabilities());
            for (Iterator iterator = disabilities.iterator(); iterator.hasNext();)
            {
                RatedDisability ratedDisability = (RatedDisability)iterator.next();
                if (ratedDisability != null)
                {
                    RatedDisability rdClone = (RatedDisability)ratedDisability.clone();
                    /* 10335 -- removed section since there is no need for an empty DiagnosticExtremity without SDS Id
                     * 
                     * if (rdClone.getDiagnosticExtremity() == null)
                    {
                        rdClone.setDiagnosticExtremity(new DiagnosticExtremity());
                    }*/
                    results.add(rdClone);
                }
            }
            return results;
        }
        else
        {
            return null;
        }
    }

    /**
     * Displays edit current 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 editEligibility(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        return mapping.findForward("success");
    }

    /**
     * Displays clinical determination data
     *
     * @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 displayClinicalDeter(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception
    {
        return mapping.findForward("success");
    }
    
    public ActionForward vcDetermination(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// Ensure we have a valid eligibility form
		EligibilityViewForm eligibiltyForm =(EligibilityViewForm) form;
		
		Person person = getSelectedPerson(request);
		VeteransChoiceInformationService vcis = this.getVeteransChoiceInformationService();
		GeocodeTransmit gt = vcis.fetchGeocodeTransmitRecord(person);
		List wts = vcis.fetchAllWaittimeRecords(person);
		eligibiltyForm.setGeocodeTransmit(gt);
		eligibiltyForm.setWaittimeList(wts);

		// query for vcis.fetAllWaittimeRecords() returns descending
		// order on PK so first list element is the latest record
		if(wts != null && wts.size() > 0){
			eligibiltyForm.setWaittime((Waittime) wts.get(0)); 
		}
		if(gt != null) {
			eligibiltyForm.setAddress(gt.getHistoricAddress().getAddress());
		}
		
		// Set the Veterans Choice Status
		eligibiltyForm.setVetChoiceStat(person.getVetChoiceStat());

		// Search for all phone types
		eligibiltyForm.setHomePhone("N/A");
		eligibiltyForm.setWorkPhone("N/A");
		eligibiltyForm.setCellPhone("N/A");
		eligibiltyForm.setTempPhone("N/A");
		
		Iterator phones = person.getPhones().iterator();
		while (phones.hasNext()) {
			Phone phone = (Phone) phones.next();
			if (phone.getType().getCode().equals(PhoneType.CODE_HOME.getCode())) {
				eligibiltyForm.setHomePhone(phone.getPhoneNumber());
			} else if (phone.getType().getCode().equals(PhoneType.CODE_BUSINESS.getCode())) {
				eligibiltyForm.setWorkPhone(phone.getPhoneNumber());
			} else if (phone.getType().getCode().equals(PhoneType.CODE_MOBILE.getCode())) {
				eligibiltyForm.setCellPhone(phone.getPhoneNumber());
			} else if (phone.getType().getCode().equals(PhoneType.CODE_TEMPORARY.getCode())) {
				eligibiltyForm.setTempPhone(phone.getPhoneNumber());				
			}
		}
		
		// Get information for Service Connection Awards
		eligibiltyForm.setServiceConnectionAward(
			person.getServiceConnectionAward() != null &&
			person.getServiceConnectionAward().getServiceConnectedIndicator() != null &&
			person.getServiceConnectionAward().getServiceConnectedIndicator() == true
				? "Yes" : "No");

		DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

		// Get the Military Service Effective Date
		try {
			eligibiltyForm.setEffectiveDate(df.format(person.getEnrollmentDetermination().getEffectiveDate()));
		} catch (Exception ex ) {
			eligibiltyForm.setEffectiveDate("N/A");
		}

		// Get the Geocode Date
		try {
			eligibiltyForm.setGeocodeDate(df.format(gt.getGeocodeDate()));
		} catch (Exception ex ) {
			eligibiltyForm.setGeocodeDate("N/A");
		}

		// Get the combat Veteran Status
		Date today = new Date();
		Date combatStatusEndDate = person.getMilitaryService().getCombatVeteranEligibilityEndDate();
		eligibiltyForm.setCombatVeteranStatus(
			(combatStatusEndDate != null && combatStatusEndDate.compareTo(today) > 0) ? "Yes" : "No"
		);

		// Get the Special Factor
		eligibiltyForm.setSpecialAuthority("No");
		Iterator specialFactors = person.getSpecialFactors().iterator();
		while (specialFactors.hasNext()) {
			SpecialFactor specialFactor = (SpecialFactor) specialFactors.next();
			if (specialFactor.getSpecialFactorIndicator().equals("Y")) {
				eligibiltyForm.setSpecialAuthority("Yes");
			};
		}
		
		
		return mapping.findForward("success");
	}

    
    public ActionForward vcDeterminationHistory(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		VCDeterminationHistoryForm history = (VCDeterminationHistoryForm) form;
		
		Person person = getSelectedPerson(request);
		VeteransChoiceInformationService vcis = this.getVeteransChoiceInformationService();
		//List vchist = vcis.fetchVCDeterminationHistory( input);
		
		List vcts = vcis.fetchVCChangeTimeLog(person);
		if(vcts == null){
			vcts = new ArrayList<String>();
			vcts.add(new Date().toString());
		}
		
		request.setAttribute("vctimelog", vcts);
		
		request.setAttribute("vchist", history);


		return mapping.findForward("success");
	}
}