package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.*;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*;
import performa.orm.*;
import performa.utils.Utils;
 

public class ConfirmDetailsFP extends SaveFP
{
    private static final LoggingArea  LOG                 =   LoggingArea.createLoggingArea("ConfirmDetailsFP");
    
    @Override 
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        ObjectTransaction   objTran     =   process.getTransaction();
        Job                 job         =   (Job) request.getAttribute("Job");
        String              email       =   job.getEmail();

        Debug.assertion(email != null, "Email not avaialble");

        email   =   email.toLowerCase();

        LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send varification email.", job , email);

        SecUser     secUser =   SecUser.searchNAME(objTran, email);

        if(secUser == null)
        {
            secUser =   SecUser.createSecUser(objTran);
            
            objTran.setAttrib(SecUser.CREATE_USER_KEY, true);

            secUser.setUserName(email);
            secUser.setEmail(email);
            secUser.setAttribute("md5:" + SecUser.FIELD_Password, CompanyUser.DEFAULT_PASSWORD);
            secUser.addRole(Utils.getRole(Utils.ROLE_APPLICANT, objTran));
        }

        //For Extension writeability
        objTran.setAttrib(SecUser.PASSWORD_WRITEABILITY_KEY, secUser.getID());
        
        Candidate   candidate   =   secUser.getExtensionOrCreate(Candidate.REFERENCE_Candidate);

        LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", secUser, " Candidate: " , candidate);
        
        request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
        request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
        
        return super.processForm(process, submission, params);
    }
}