package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.*;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*;
import performa.orm.Candidate;
import performa.orm.Job;
import performa.orm.JobApplication;


public class ResetPasswordFP extends ORMProcessFormProcessor
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Job                 job         =   (Job) request.getAttribute("Job");
        Candidate           candidate   =   (Candidate) request.getAttribute("NewCandidate");
        String              nextPage    =   (String) request.getAttribute("nextPage");

        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1, "Inside ResetPasswordFP for ", job, candidate);
        
        SecUser             secUser     =   candidate.getUser();
            
        if(CollectionUtils.equals(job.getPassword(), job.getConfirmPassword()))
        {
            secUser.setAttribute("md5:" + SecUser.FIELD_Password, job.getPassword());
            candidate.setIsAccountVerified(Boolean.TRUE);
        }

        request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
        request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
        
        process.completeAndRestart();
        process.setAttributeIgnoreTX("Job", job);
        
        return new ProcessRedirectResult(nextPage, new String[0]);
    }
    
    
    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Job                 job         =   (Job) request.getAttribute("Job");
        Candidate           candidate   =   (Candidate) request.getAttribute("NewCandidate");
        
        if(candidate!=null)
        {
            BusinessObjectParser.assertFieldCondition(job.getPassword()!= null, job, Job.FIELD_Password, "mandatory", exceptions, true, request);
            BusinessObjectParser.assertFieldCondition(job.getConfirmPassword()!= null, job, Job.FIELD_ConfirmPassword, "mandatory", exceptions, true, request);
            BusinessObjectParser.assertFieldCondition(CollectionUtils.equals(job.getPassword(), job.getConfirmPassword()), job, Job.FIELD_ConfirmPassword, "passwordNotMatch", exceptions, true, request);
        }
        
        super.validate(process, submission, exceptions, params);
    }
}
