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.objstore.rdbms.filters.EqualsFilter;
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();
        Job                 job             =   (Job) request.getAttribute("Job");
        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;

        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);
        }
        
        if(fromCoverLetter)
        {
            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");
        String              nextPage        =   (String) request.getAttribute("nextPage");
        Candidate           candidate       =   (Candidate) request.getAttribute("Candidate");

        if(isVerify)
        {
            SecUser         secUser     =   candidate.getUser();
            
            boolean     isPwdMatch  =   secUser.checkPassword(job.getPassword());

            if(!isPwdMatch)
            {
                throw new BusinessException("Password doesnot match with the records !!");
            }
            
            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);
                
                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.setAttribute("JobApplication", jobApplication);
        request.setAttribute("nextPage", nextPage + "&JobID=" + job.getObjectID());
        
        return super.processForm(process, submission, params);
        
//        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.");
        }
    }
}