package performa.batch;

import java.util.Date;
import javax.activation.DataSource;
import oneit.appservices.batch.ORMBatch;
import oneit.components.InitialisationParticipant;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.Emailer;
import oneit.email.TextDataSource;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.rdbms.filters.LessThanEqualFilter;
import oneit.utils.InitialisationException;
import oneit.utils.StringUtils;
import oneit.utils.parsers.FieldException;
import performa.orm.JobApplication;
import performa.orm.ScheduledEmail;
import performa.orm.SentEmail;
import performa.orm.types.PlaceholderOptions;
import oneit.net.LoopbackHTTP;
import oneit.utils.RandomStringGen;
import performa.orm.Candidate;
import performa.orm.Job;
import performa.utils.Utils;


public class MessagingEngineBatch extends ORMBatch implements InitialisationParticipant
{
    private Emailer  emailEngine;
    
    public static LoggingArea MESSAGING_ENGINE_BATCH = LoggingArea.createLoggingArea("MessagingEngineBatch");

    @Override
    public void run(ObjectTransaction ot) throws StorageException, FieldException
    {
        LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "RUNNING Messaging Engine Batch");

        ScheduledEmail[]    scheduledEmails =   ScheduledEmail.SearchByAll().andScheduledDate(new LessThanEqualFilter<>(new Date())).search(ot);
        
        for (ScheduledEmail scheduledEmail : scheduledEmails)
        {
            LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "Starting to create email for scheduled email : " , scheduledEmail);
            
            JobApplication  jobApplication      =   scheduledEmail.getJobApplication();
            Job             job                 =   jobApplication.getJob();
            Candidate       candidate           =   jobApplication.getCandidate();
            
            // for existing users without a verification code
            if( candidate.getVerificationKey() == null)
            {
                candidate.setVerificationKey(new RandomStringGen().generateAlphaNum(6));
            }
                
            String          jobLink             =   LoopbackHTTP.getRemoteAccessURL() 
                                                        + Utils.APPLICANT_LINK
                                                        + "?id=" + job.getID() 
                                                        + "&key=" + job.getRandomKey() 
                                                        + "&aid=" + candidate.getID()
                                                        + "&pin=" + candidate.getVerificationKey();
            
            // replace tags
            String          messageContent      =   StringUtils.replace(scheduledEmail.getMessageContent(), 
                                                                new String[] {PlaceholderOptions.FIRST_NAME.getPlaceholder(), 
                                                                                PlaceholderOptions.SURNAME.getPlaceholder(), 
                                                                                PlaceholderOptions.EMAIL_ADDRESS.getPlaceholder(), 
                                                                                PlaceholderOptions.LOCATION.getPlaceholder(), 
                                                                                PlaceholderOptions.JOB_TITLE.getPlaceholder(), 
                                                                                PlaceholderOptions.JOB_REFERENCE.getPlaceholder(),
                                                                                PlaceholderOptions.HIRING_TEAM.getPlaceholder(),
                                                                                PlaceholderOptions.JOB_LINK.getPlaceholder()},
                                                                new String[] {candidate.getFirstName(), 
                                                                                candidate.getUser().getLastName(), 
                                                                                candidate.getUser().getEmail(), 
                                                                                StringUtils.subNulls(job.getGoogleAddressText(), ""), 
                                                                                job.getJobTitle(), 
                                                                                StringUtils.subNulls(job.getReferenceNumber(), ""),
                                                                                job.getHiringTeam().getHiringTeamName(), 
                                                                                jobLink});
            
            LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "Replaced tags of message content : " , messageContent);

            TextDataSource  mesgBodyDataSource  =   new TextDataSource(messageContent, "text/html", "");               
            String          toEmail             =   candidate.getUser().getEmail();
            String          fromEmail           =   "Matchd<help@matchd.com>";
            String          replyToEmail        =   job.getCreatedBy().getUser().getEmail();
            SentEmail       sentEmail           =   SentEmail.createSentEmail(ot);
            
            emailEngine.sendEmail(new String[] {toEmail}, fromEmail, new String[] {replyToEmail}, scheduledEmail.getSubject() , new DataSource[]{mesgBodyDataSource});
            
            LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "Email sent to : " , toEmail, " from : ", fromEmail);
            
            sentEmail.setSubject(scheduledEmail.getSubject());
            sentEmail.setSentDate(new Date());
            sentEmail.setApplicationStatus(scheduledEmail.getApplicationStatus());
            sentEmail.setMessageContent(messageContent);
            sentEmail.setEmailTo(toEmail);
            sentEmail.setJobApplication(jobApplication);
                    
            LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "SentEmail object created to store sent email details : " , sentEmail);
            
            scheduledEmail.delete();
        }
        
        LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "End of Messaging Engine Batch");
    }
    
    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        super.init(context);
        
        emailEngine = (Emailer) context.getSingleChild("EmailEngine");
    } 
}