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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.model.AbstractKeyedEntity;
import gov.va.med.fw.model.EntityKey;

import gov.va.med.esr.common.model.lookup.Capability;
import gov.va.med.esr.common.model.security.CapabilitySet;
import gov.va.med.esr.common.model.security.ESRRolePrincipalImpl;

import gov.va.med.esr.ui.common.action.AbstractAction;
import gov.va.med.esr.ui.common.beans.EntityHistory;
import gov.va.med.esr.ui.common.beans.FieldHistoryInfo;
import gov.va.med.esr.ui.common.beans.FormattingTableRow;

public class AbstractUserProfileAction extends AbstractAction {
    
    public static final String ERRORS_ACTIVE_DATE_PAST = "error.activeDatePast";
    public static final String ERRORS_INACTIVE_DATE_PAST = "error.inactiveDatePast";
    
    public ActionForward cancel(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        //form is cleared automatically as it is in the request scope
        clearSessionData(request);
        return mapping.findForward(FWD_CANCEL);
    }
    public ActionForward clear(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        //form is cleared automatically as it is in the request scope
        form.reset(mapping,request);
        return mapping.findForward(FWD_CLEAR);
    }        
    
    /**
     * returned after viewing history for an existing entity
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward returnToEdit(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        //if we have bothe updated and pristine convert updated entity
        //if just have pristine convert pristine
        //else forward to list
        AbstractKeyedEntity pristine = (AbstractKeyedEntity) getPristineEntity(request);
        AbstractKeyedEntity updated = (AbstractKeyedEntity) getUpdatedEntity(request);
        if (pristine == null) {
            return discard(mapping, form, request, response);
        }
                
        if (updated != null && 
                updated.getClass().getName().equals(pristine.getClass().getName())){
            //if the primary keys match convert updated
            EntityKey key1 = pristine.getEntityKey();
            EntityKey key2 = updated.getEntityKey();
            if (key1.getKeyValue().equals(key2.getKeyValue())) {
                return revise(mapping,form,request,response);
            }
        }
        //clone pristine and
        setUpdatedEntity(request,pristine.clone());
        return revise(mapping,form,request,response);
    }
    
    /**
     * optional method to be implemented by subclasses
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward revise(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        return null;
    }
    /**
     * optional method to be implemented by subclasses
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */    
    public ActionForward discard(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        return null;
    }       
    public void afterPropertiesSet() throws Exception {
    }
    protected void clearSessionData(HttpServletRequest request) throws Exception
    {
        setPristineEntity(request,null);
        setUpdatedEntity(request,null);
    }
    
    protected void populateReferenceData(HttpServletRequest request) throws Exception
    {
        //get all Capabilities, sets and roles
        List set = getUserAdminService().getAllCapabilitySets();
        List roles = getUserAdminService().getAllRoles();
        request.getSession().setAttribute("REF_CAPABILITY_SETS",conevrtToKeyMap(set));
        request.getSession().setAttribute("REF_ROLES",conevrtToKeyMap(roles));         
    }

    
    protected  List processCapabilitySets(List sets){
        List filedHistoryList = new ArrayList ();
        if (sets != null && sets.size() > 0) {
            FormattingTableRow infoBean = new FormattingTableRow("label.assignedCapabilitySets");
            filedHistoryList.add(infoBean);
            for (Iterator i=sets.iterator(); i.hasNext();) {
                EntityHistory entityHistory = (EntityHistory)i.next();
                CapabilitySet current = (CapabilitySet) entityHistory.getCurrent();
                CapabilitySet previous = (CapabilitySet) entityHistory.getPrevious();
                String curValue = (current == null ? "" : current.getName());
                String oldValue = (previous == null ? "" : previous.getName());
                filedHistoryList.add(new FieldHistoryInfo("label.name",curValue,oldValue));
            }
        }
        return filedHistoryList;
    }
    
    protected  List processRoles(List roles){
        List filedHistoryList = new ArrayList ();
        if (roles != null && roles.size() > 0) {
            FormattingTableRow infoBean = new FormattingTableRow("label.assignedRoles");
            filedHistoryList.add(infoBean);
            
            for (Iterator i=roles.iterator(); i.hasNext();) {
                EntityHistory entityHistory = (EntityHistory)i.next();
                ESRRolePrincipalImpl current = (ESRRolePrincipalImpl) entityHistory.getCurrent();
                ESRRolePrincipalImpl previous = (ESRRolePrincipalImpl) entityHistory.getPrevious();
                String curValue = (current == null ? "" : current.getName());
                String oldValue = (previous == null ? "" : previous.getName());
                filedHistoryList.add(new FieldHistoryInfo("label.name",curValue,oldValue));
            }
        }
        return filedHistoryList;
    }    
    protected  List processCapabilities(List capabilityList){
        List filedHistoryList = new ArrayList ();
        if (capabilityList != null && capabilityList.size() > 0) {
            FormattingTableRow infoBean = new FormattingTableRow("label.assignedCapabilities");
            filedHistoryList.add(infoBean);            
            for (Iterator i=capabilityList.iterator(); i.hasNext();) {
                EntityHistory entityHistory = (EntityHistory)i.next();
                Capability current = (Capability) entityHistory.getCurrent();
                Capability previous = (Capability) entityHistory.getPrevious();
                String curValue = (current == null ? "" : current.getName());
                String oldValue = (previous == null ? "" : previous.getName());
                filedHistoryList.add(new FieldHistoryInfo("label.name",curValue,oldValue));
            }
        }
        return filedHistoryList;
    }
    
    private Map conevrtToKeyMap(List list) {
        Map map = new HashMap();
        if (list == null || list.size() == 0)
            return map;
        for (Iterator i=list.iterator(); i.hasNext();) {
            AbstractKeyedEntity entity = (AbstractKeyedEntity) i.next();
            map.put(entity.getEntityKey().getKeyValueAsString(),entity);
        }
        return map;
    }        
}
