package performa.form;

import java.util.Date;
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.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.utils.*;
import performa.orm.*;
import performa.utils.Utils;
import performa.utils.WebUtils;
 

public class SendVerificationMailFP extends SaveFP
{
    private static LoggingArea  LOG                 =   LoggingArea.createLoggingArea("SendVerificationLink");
    private static final String DEFAULT_PASSWORD    =   "Talentology123";
    protected ConfigurableArticleTemplateEmailer  emailer;

    
    @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.isEmailFound(), job, Job.FIELD_Email, "emailExists", 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();
        ObjectTransaction   objTran     =   process.getTransaction();
        Job                 job         =   (Job) request.getAttribute("Job");
        String              email       =   job.getEmail();
        
        Debug.assertion(email != null, "Email not avaialble");
        
        LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send varification email.", job , email);
        
        SecUser             secUser     =   SecUser.searchNAME(objTran, email);
        
        Debug.assertion(secUser == null, "user available", email);
            
        LogMgr.log(LOG, LogLevel.PROCESSING1, "Inside SendVerificationMailFP for send account verification mail for ", email);


        SecUser     newSecUser  =   SecUser.createSecUser(objTran);

        newSecUser.setUserName(email);
        newSecUser.setAttribute("md5:" + SecUser.FIELD_Password, DEFAULT_PASSWORD);

        LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", newSecUser);

        newSecUser.addRole(Utils.getRole(Utils.ROLE_APPLICANT, objTran));

        Candidate   candidate   =   newSecUser.getExtensionOrCreate(Candidate.REFERENCE_Candidate);

        sendVerificationMail(candidate, job, request);
        
        request.setAttribute("nextPage", request.getAttribute("nextPage") + "&JobID=" + job.getID());

        return super.processForm(process, submission, params);
    }
    
        
    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        super.init(context);
        
        emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountVerificationEmailer"));
    }
    
    
    protected void sendVerificationMail(Candidate candidate, Job job, HttpServletRequest request) throws BusinessException
    {
        if(candidate.getIsAccountVerified()!=Boolean.TRUE)
        {
            try
            {
                LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending verification mail from  SendVerificationMailFP to :: ", candidate);

                Article         verificationArticle =   WebUtils.getArticleByShortCut(candidate.getTransaction(), WebUtils.APPLY_JOB);
                RandomStringGen random              =   new RandomStringGen();

                //set verification key and send mail time
                candidate.setVerificationKey(random.generateAlphaNum(6));
                candidate.setVerificationMailSendDate(new Date());

                String          link                =   LoopbackHTTP.getRemoteAccessURL(request) 
                                                            + verificationArticle.getLink(request, CollectionUtils.EMPTY_MAP, "/") 
                                                            + "?cms%2Erm=SignIn"
                                                            + "&id=" + job.getID() 
                                                            + "&key=" + job.getRandomKey() 
                                                            + "&aid=" + candidate.getID()
                                                            + "&pin=" + candidate.getVerificationKey();
                Map             defaultParams       =   CollectionUtils.mapEntry("link", link).toMap(); 
                ObjectTransform transform           =   Utils.createCompoundTransform(defaultParams, candidate);

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

                LogMgr.log(LOG, LogLevel.PROCESSING1, "Sent verification mail successfully from " + SendVerificationMailFP.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 Talantology for more details.");
            }
        }
        else
        {
            LogMgr.log(LOG, LogLevel.PROCESSING1, "Call from " + SendVerificationMailFP.class + ". Account is already verified  for candidate :: ", candidate);
        }
    }
}