package performa.form;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.appservices.accesslog.AccessLog;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.security.AuthorisationToken;
import oneit.security.LoginProcessor;
import oneit.security.SecUser;
import oneit.security.jsp.MaintainUserFP;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessFormProcessor;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.servlets.utils.decorator.LoggingDecorator;
import oneit.servlets.utils.session.SessionManager;
import oneit.utils.BusinessException;
import performa.orm.HiringTeam;


public class AssumeHTAdminFP extends ORMProcessFormProcessor
{
    public static final String  UNASSUME_SEC_USER_ID = "oeit.unassumeSecUser";

    private LoginProcessor  loginFP;
    
    @Override
    public SuccessfulResult processForm(ORMProcessState process,
                                        SubmissionDetails submission,
                                        Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        HiringTeam          hiringTeam  =   (HiringTeam) request.getAttribute("HiringTeam");
        SecUser             editor      =   (SecUser) request.getAttribute(AuthorisationToken.AUTH_TOKEN_ID);
        SecUser             secUser     =   hiringTeam.getAddedByUser() != null ? hiringTeam.getAddedByUser().getUser() : null;
        
        if (secUser == null)
        {
            return null;
        }

        process.getTransaction().assertPrivilege("securityAssumeUser");
        
        LogMgr.log( MaintainUserFP.LOG, LogLevel.BUSINESS1, "Assuming: ", secUser.getUserName(), " emp#: ", secUser.getObjectID(), " by ", editor );

        SecUser             toAssume = (SecUser)secUser.getInTransaction(ObjectTransaction.getTransaction());

        AccessLog.getAccessLog().recordAccess("LOGIN", "Assume.jsp", toAssume.getAuthToken(), LoggingDecorator.getSessionID(submission.getRequest()), AccessLog.ACCESS_RESULT_OK, submission.getRequest().getRemoteAddr());

        SessionManager.clearSession(request.getSession());
        
        request.getSession().setAttribute(UNASSUME_SEC_USER_ID, editor);
        request.getSession().setAttribute(SecUser.SEC_USER_ID, toAssume);
        request.getSession().setAttribute(SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
        request.getSession().setAttribute("SelectedHiringTeam", hiringTeam);

        return loginFP.processSuccessfulLogin(submission, new HashMap(), toAssume);
    }
    
}
