package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.business.content.Article;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.email.ConfigurableEmailerException;
import oneit.logging.*;
import oneit.net.LoopbackHTTP;
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.orm.*;
import performa.utils.Utils;
import performa.utils.WebUtils;
 

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

        if(isVerify)
        {
            BusinessObjectParser.assertFieldCondition(secUser.checkPassword(job.getPassword()) , job, Job.FIELD_Password,  "invalid", exceptions, true, request);
        }
        
        if(fromCoverLetter && job.getRequireCV())
        {
            BusinessObjectParser.assertFieldCondition(jobApplication.getCV() != null , jobApplication, JobApplication.FIELD_CV, "uploadCV", exceptions, true, request);
            BusinessObjectParser.assertFieldCondition(jobApplication.getCoverLetter() != null , jobApplication, JobApplication.FIELD_CoverLetter, "uploadCover", 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");
        JobApplication      jobApplication  =   (JobApplication) request.getAttribute("JobApplication");
        Candidate           candidate       =   (Candidate) request.getAttribute("Candidate");

        if(isVerify)
        {
            SecUser     secUser     =   candidate.getUser();

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

            candidate.setIsAccountVerified(Boolean.TRUE);
                
            sendMail(candidate, job, request);
                
            request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
            request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);

            LogMgr.log(LOG, LogLevel.PROCESSING1, "Verified User ", job, secUser);
        }
        
        // storing candidate location in application for distance calculation to be accurate even if user edits 
        // location in the next application
        jobApplication.setGoogleAddressText(candidate.getGoogleAddressText());
        
        return super.processForm(process, submission, params);
    }

    
    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        super.init(context);
        
        emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("ApplicantAccountCreatedEmailer"));
    }
    
    
    protected void sendMail(Candidate candidate, Job job, HttpServletRequest request) throws BusinessException
    {
        try
        {
            LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending Account Created mail from  VerifyIdentityFP to :: ", candidate);
            
            Article         applyJobArticle =   WebUtils.getArticleByShortCut(candidate.getTransaction(), WebUtils.APPLY_JOB);
            String          link            =   LoopbackHTTP.getRemoteAccessURL(request) 
                                                            + applyJobArticle.getLink(request, CollectionUtils.mapEntry("cms.rm", WebUtils.FORGOT_PASSWORD).toMap(), "/")
                                                            + "&id=" + job.getID() 
                                                            + "&key=" + job.getRandomKey();
            Map             defaultParams   =   CollectionUtils.mapEntry("link", link).toMap(); 
            ObjectTransform transform       =   Utils.createCompoundTransform(defaultParams, candidate.getUser());

            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 Matchd for more details.");
        }
    }
}