package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.email.ConfigurableEmailerException;
import oneit.logging.*;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*;
import performa.intercom.utils.IntercomUtils;
import performa.orm.*;
import performa.utils.Utils;
 

public class VerifyIdentityFP extends ORMProcessFormProcessor
{
    private static LoggingArea  LOG =   LoggingArea.createLoggingArea("VerifyIdentity");
    protected ConfigurableArticleTemplateEmailer  emailer;
    
    @Override
    protected Map validate(SubmissionDetails submission, MultiException exceptions) 
    {
        HttpServletRequest  request     =   submission.getRequest();
        Boolean             isVerify    =   CollectionUtils.equals(request.getAttribute("isVerify"), Boolean.TRUE);
        Job                 job         =   (Job) request.getAttribute("Job");
        Candidate           candidate   =   (Candidate) request.getAttribute("Candidate");
        SecUser             secUser     =   candidate.getUser();

        if(secUser.getUserName() != null)
        {
            BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(secUser.getUserName()), job, Job.FIELD_Email, "invalid", exceptions, true, request);
        }
        
        BusinessObjectParser.assertFieldCondition(secUser.getFirstName() != null, secUser, SecUser.FIELD_FirstName, "mandatory", exceptions, true, request);
        BusinessObjectParser.assertFieldCondition(secUser.getLastName() != null, secUser, SecUser.FIELD_LastName, "mandatory", exceptions, true, request);
        
        
        if(isVerify)
        {
            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);
        
        }
        
        return super.validate(submission, exceptions);
    }

    
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Boolean             isVerify    =   CollectionUtils.equals(request.getAttribute("isVerify"), Boolean.TRUE);
        Job                 job         =   (Job) request.getAttribute("Job");
        String              nextPage    =   (String) request.getAttribute("nextPage");

        if(isVerify)
        {
            Candidate       candidate   =   (Candidate) request.getAttribute("Candidate");
            SecUser         secUser     =   candidate.getUser();

            LogMgr.log(LOG, LogLevel.PROCESSING1, "Verifing User", job, secUser);

            if(CollectionUtils.equals(job.getPassword(), job.getConfirmPassword()))
            {
                secUser.setAttribute("md5:" + SecUser.FIELD_Password, job.getPassword());
                candidate.setIsAccountVerified(Boolean.TRUE);
                
                sendMail(candidate, request);
                                
                // Create a applicant user in intercom
                IntercomUtils.createIntercomUser(secUser, "Applicant", null);
                
                request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
                request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
//                request.setAttribute("nextPage", nextPage + "&JobID=" + job.getObjectID());

                LogMgr.log(LOG, LogLevel.PROCESSING1, "Password resetted", job, secUser);
            }
        }
        
        process.completeAndRestart();

        return new ProcessRedirectResult(nextPage + "&JobID=" + job.getObjectID(), new String[0]);
    }

    
    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        super.init(context);
        
        emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountCreatedEmailer"));
    }
    
    
    protected void sendMail(Candidate candidate, HttpServletRequest request) throws BusinessException
    {
        try
        {
            LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending Account Created mail from  VerifyIdentityFP to :: ", candidate);

            Map             defaultParams       =   CollectionUtils.EMPTY_MAP;
            ObjectTransform transform           =   Utils.createCompoundTransform(defaultParams, candidate);

            Utils.sendMail(emailer, transform, new String[]{candidate.getUser().getUserName()}, null, candidate);

            LogMgr.log(LOG, LogLevel.PROCESSING1, "Sent Account Created mail successfully from " + VerifyIdentityFP.class + " to :: ", candidate);
        }
        catch (ConfigurableEmailerException ex)
        {
            LogMgr.log(LOG, LogLevel.SYSTEMERROR1, ex, "Error occured while sending mail for Candidate :: " + candidate);

            throw new BusinessException("We are unable to send mail. Please try again or contact Talentology for more details.");
        }
    }
}