package performa.form;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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.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);

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

        Candidate   candidate   =   secUser.getExtensionOrCreate(Candidate.REFERENCE_Candidate);

        LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", secUser);
        
        Set<String> attribsToRestore    =   new HashSet<>();
        
        attribsToRestore.add("Job");
        attribsToRestore.add("NewCandidate");
        request.setAttribute("attribNamesToRestore", attribsToRestore);
        process.setAttribute("NewCandidate",candidate);    
        
        return super.processForm(process, submission, params);
    }
}