package performa.form;

import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.AuthorisationToken;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.ORMProcessFormProcessor;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.ProcessRedirectResult;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*;
import performa.orm.Candidate;
import performa.orm.Job;
 

public class SignInCandidateFP extends ORMProcessFormProcessor
{

    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
    {
        HttpServletRequest  request = submission.getRequest();
        Job                 job     = (Job) request.getAttribute("Job");
        
        BusinessObjectParser.assertFieldCondition(job.getEmail()!= null,
                                            job,
                                            job.FIELD_Email,
                                            "mandatory",
                                            exceptions,
                                            true,
                                            request);
        
        super.validate(process, submission, exceptions, params);
    }

    
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest              request     =   submission.getRequest();
        Job                             job         =   (Job) request.getAttribute("Job");
        String                          nextPage    =   (String) request.getAttribute("nextPage");
        Tuple.T2<Candidate, Boolean>    tuple       =   job.getUserOrCreate();
        Candidate                       candidate   =   tuple.get0();
        SecUser                         secUser     =   candidate.getUser();
 
//        request.getSession().invalidate();
        request.getSession().setAttribute (AuthorisationToken.AUTH_TOKEN_ID, secUser);

        // place the user on the session
        request.getSession ().setAttribute (SecUser.SEC_USER_ID, secUser);

        // This is only to help with the tomcat manager, so you can see which user belongs to which session
        request.getSession ().setAttribute (SecUser.SEC_USER_ID+".desc", secUser.getDescription());
        request.getSession ().setAttribute (SecUser.SEC_USER_ID+".loggedin", ""+new Date());
        request.getSession ().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);

        process.setAttribute("Candidate", candidate);

        return new ProcessRedirectResult(nextPage, new String[]{});
    }
}