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.intercom.utils.IntercomUtils;
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();
        Job                 job         =   (Job) request.getAttribute("Job");
        Candidate           candidate   =   (Candidate) request.getAttribute("Candidate");
        SecUser             secUser     =   candidate.getUser();
        Boolean             isVerify    =   CollectionUtils.equals(request.getAttribute("isVerify"), Boolean.TRUE);

        BusinessObjectParser.assertFieldCondition(secUser.getEmail() != null , job, Job.FIELD_Email, "mandatory", exceptions, true, request);
        BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(secUser.getEmail()), 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(candidate.isTrue(candidate.getPrivacyPolicyAgreed()), candidate, Candidate.FIELD_PrivacyPolicyAgreed, "agreePrivacy", exceptions, true, request);
            BusinessObjectParser.assertFieldCondition(candidate.isTrue(candidate.getConditionsAgreed()), candidate, Candidate.FIELD_ConditionsAgreed, "agreeTerms", 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");
        String              nextPage        =   (String) request.getAttribute("nextPage");
        Candidate           candidate       =   (Candidate) request.getAttribute("Candidate");

        if(isVerify)
        {
            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, job, request);
                                
                // Create a applicant user in intercom
                IntercomUtils.createIntercomUser(secUser, "Applicant", null, candidate.getPhone());
                
                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);
//            }
        }
        
        // storing candidate location in application for distance calculation to be accurate even if user edits 
        // location in the next application
        jobApplication.setGoogleAddressText(candidate.getGoogleAddressText());
        
        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("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.");
        }
    }
}