/*
 * Created on Dec 27, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.va.med.esr.ui.signature.action;

//Java classes
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

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

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

import gov.va.med.fw.model.EntityKeyFactory;
import gov.va.med.fw.security.SecurityContext;
import gov.va.med.fw.security.SecurityContextHelper;
import gov.va.med.fw.security.UserPrincipal;

import gov.va.med.esr.ui.common.action.PersonAbstractAction;
import gov.va.med.esr.ui.conversion.UIConversionService;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.SignatureImage;
import gov.va.med.esr.common.model.lookup.SignatureIndicator;
import gov.va.med.esr.service.FinancialsService;

/**
 * @author DNS   CHENB
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SignatureEditAction extends PersonAbstractAction {
    private FinancialsService financialsService;

	/**
	 * 
	 */
	public SignatureEditAction() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * edit eligibility.
	 * 
	 * @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 java.lang.Exception Thrown if failed to process 
	 */
	public ActionForward edit( ActionMapping mapping, 
	      					    ActionForm form,
	      					     HttpServletRequest request, 
	      					     HttpServletResponse response ) throws Exception {
	   //TODO use apadter.
		SignatureEditForm signatureForm = (form instanceof SignatureEditForm) ? (SignatureEditForm)form : null;
		Validate.notNull(signatureForm, "SignatureEditForm bean is null.");

		String selectedSignatureKey = signatureForm.getSelectedSignatureKey();
		
		Person person = (Person)getSelectedPerson( request );
		
		SignatureImage signature = getSignatureImage(person, selectedSignatureKey);
		
		UIConversionService uiConversionService = (UIConversionService)conversionService;
		uiConversionService.convert(signature, signatureForm);

		return mapping.findForward("edit");
	}		

	private SignatureImage getSignatureImage(Person person, String selectedSignatureKey)
	{
		if (person.getSignatureImages() != null)
		{
			return person.getSignatureImageByEntityKey(
					EntityKeyFactory.createEntityKey(new BigDecimal(selectedSignatureKey), SignatureImage.class));
//            Iterator iterImage = person.getSignatureImages().iterator();
//
//            if (iterImage.hasNext()) {
//                return (SignatureImage) iterImage.next();
//            }
		}
		return null;
	}
	/**
	 * update eligibility.
	 * 
	 * @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 java.lang.Exception Thrown if failed to process 
	 */
	public ActionForward update( ActionMapping mapping, 
	      					    ActionForm form,
	      					     HttpServletRequest request, 
	      					     HttpServletResponse response ) throws Exception {
	   //TODO use apadter.
		SignatureEditForm signatureForm = (form instanceof SignatureEditForm) ? (SignatureEditForm)form : null;
		Validate.notNull(signatureForm, "SignatureEditForm bean is null.");

		String selectedSignatureKey = signatureForm.getSelectedSignatureKey();

		Person person = (Person)getSelectedPerson( request );
		SignatureImage signature = getSignatureImage(person, selectedSignatureKey);
				
		if (signature != null)
		{
			SignatureIndicator indicator = signature.getSignatureIndicator();

			UIConversionService uiConversionService = (UIConversionService)conversionService;
			uiConversionService.convert(signatureForm, signature);
	        
			if (signature.getSignatureIndicator() != null &&
				!signature.getSignatureIndicator().equals(indicator))
			{
				SecurityContext securityContext = SecurityContextHelper.getSecurityContext();
				UserPrincipal user = securityContext.getUserPrincipal();
				signature.setUser(user.getName());
            }

            //Call SignatureService
            // Call service layer here
            Person updatedPerson = getFinancialsService().updatePersonSignature(person);

            // Store updated person in the cache
            updateSelectedPerson(request, updatedPerson);
		}
		else
        {
            log.error( "update signature: Can not find SignatureImage with selected ImageID ");
        }

		return mapping.findForward("update");
	}		

	/**
	 * cancel eligibility.
	 * 
	 * @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 java.lang.Exception Thrown if failed to process 
	 */
	public ActionForward cancel( ActionMapping mapping, 
	      					    ActionForm form,
	      					     HttpServletRequest request, 
	      					     HttpServletResponse response ) throws Exception {
		return mapping.findForward("cancel");
	}		

    /**
     * @return Returns the financialsService.
     */
    public FinancialsService getFinancialsService()
    {
        return financialsService;
    }

    /**
     * @param financialsService The financialsService to set.
     */
    public void setFinancialsService(FinancialsService financialsService)
    {
        this.financialsService = financialsService;
    }

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub

	}
	/**
     * handle one form have multiple submit button.
     * 
     * @see org.apache.struts.actions.LookupDispatchAction#getKeyMethodMap()
     * @return key map
     */
	protected Map getKeyMethodMap() {
		Map map = new HashMap();
		map.put("button.cancel","cancel");
		map.put("button.update","update");
		map.put("link.edit","edit");
		
		return map;
	}

}
