package performa.form;

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

public class SignInCandidateFP extends LoginProcessor
{
    private static final String DEFAULT_PASSWORD    =   "Talentology123";
    
    @Override
    public SuccessfulResult processForm(SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        ORMProcessState     process     =   (ORMProcessState)ProcessDecorator.getDefaultProcess(request);
        ObjectTransaction   objTran     =   process.getTransaction();
        Job                 job         =   (Job) request.getAttribute("Job");
        String              nextPage    =   (String) request.getAttribute("nextPage");
        String              email       =   job.getEmail();
        
        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1, "Inside SignInCandidateFP for ", job, " Email:", email);
        
        SecUser             secUser     =   SecUser.searchNAME(objTran, email);
        final   Map         userMap     =   new HashMap();
        
        if(secUser == null)
        {
            objTran.runInNewTX(new TransactionTask()
            {
                @Override
                public void run(ObjectTransaction newObjTran) throws FieldException, StorageException
                {
                    SecUser newSecUser  =   SecUser.createSecUser(newObjTran);

                    newSecUser.setUserName(email);
                    newSecUser.setAttribute("md5:" + SecUser.FIELD_Password, DEFAULT_PASSWORD);

                    LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1, "New user created :: ", newSecUser);

                    newSecUser.addRole(Utils.getRole(Utils.ROLE_APPLICANT, newObjTran));
                    newSecUser.getExtensionOrCreate(Candidate.REFERENCE_Candidate);

                    userMap.put("username", newSecUser.getUserName());
                    userMap.put("password", DEFAULT_PASSWORD);
                }
            });
        }
        else if(!secUser.hasPrivilege(Utils.PRIV_ACCESS_APPLICANT_PORTAL) || secUser.getExtension(Candidate.REFERENCE_Candidate) == null)
        {
            throw new BusinessException("You are not allowed to access this portal");
        }
        else
        {
            LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1, "Existing user skipping password check :: ", secUser);
            
            userMap.put("username", secUser.getUserName());
            userMap.put("password", DEFAULT_PASSWORD);
        }
        request.setAttribute("nextPage", nextPage + "&JobID=" + job.getObjectID());
        
        return super.processForm(submission, userMap);
    }

    @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);
        
        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);
    }
}