package performa.form;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.*;
import oneit.objstore.*;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.*;
import oneit.servlets.forms.*;
import oneit.utils.*;
import oneit.utils.parsers.FieldException;
import performa.orm.*;
import performa.utils.Utils;
 

public class SignInCandidateFP extends LoginProcessor
{
    @Override
    public SuccessfulResult processForm(SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Job                 job         =   (Job) request.getAttribute("Job");
        String              nextPage    =   (String) request.getAttribute("nextPage");
        String              email       =   job.getEmail();
        final   Map         userMap     =   new HashMap();

        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1, "Inside SignInCandidateFP for ", job, " Email:", email);

        userMap.put("username", job.getEmail().toLowerCase());
        userMap.put("password", job.getPassword());

        request.setAttribute("nextPage", nextPage + "&JobID=" + job.getObjectID());
        
        return super.processForm(submission, userMap);
    }
    
    
    @Override
    protected void checkUserCanLogin(ObjectTransaction trans, SecUser userToCheck, SubmissionDetails submission, Map requestParams) throws FieldException, MultiException
    {
        super.checkUserCanLogin(trans, userToCheck, submission, requestParams);
        
        Candidate   candidate   =   userToCheck.getExtension(Candidate.REFERENCE_Candidate);
        
        if(!Utils.checkApplicantPortalAccess(userToCheck) ||  candidate == null || candidate.getIsAccountVerified()!=Boolean.TRUE)
        {
            throw new FieldException("You're not an authorised user to access this portal.", SecUser.FIELD_UserName);
        }
    }
    
    
    @Override
    protected Map validate(SubmissionDetails submission, MultiException exceptions)
    {
        HttpServletRequest  request     =   submission.getRequest();
        Job                 job         =   (Job) request.getAttribute("Job");
        
        BusinessObjectParser.assertFieldCondition(job.getEmail()!= null, job, Job.FIELD_Email, "mandatory", exceptions, true, request);
        BusinessObjectParser.assertFieldCondition(job.getPassword()!= null, job, Job.FIELD_Password, "mandatory", exceptions, true, request);

        return super.validate(submission, exceptions);
    }
    
    
    @Override
    public SuccessfulResult processSuccessfulLogin(SubmissionDetails submission, Map requestParameters, SecUser secUser) throws BusinessException
    {
        return new RedirectResult((String)submission.getRequest().getAttribute("nextPage"), null);
    }
}