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;


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();
            // 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()},
                                                                new String[] {jobApplication.getCandidate().getFirstName(), 
                                                                                jobApplication.getCandidate().getUser().getLastName(), 
                                                                                jobApplication.getCandidate().getUser().getEmail(), 
                                                                                StringUtils.subNulls(jobApplication.getJob().getGoogleAddressText(), ""), 
                                                                                jobApplication.getJob().getJobTitle(), 
                                                                                StringUtils.subNulls(jobApplication.getJob().getReferenceNumber(), "")});
            
            LogMgr.log (MESSAGING_ENGINE_BATCH, LogLevel.PROCESSING1, "Replaced tags of message content : " , messageContent);
            
            TextDataSource  mesgBodyDataSource  =   new TextDataSource(StringUtils.fromHTML(messageContent));               
            String          toEmail             =   jobApplication.getCandidate().getUser().getEmail();
            String          fromEmail           =   "Matchd<help@matchd.com>";
            String          replyToEmail        =   jobApplication.getJob().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");
    } 
}
