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.parsers.FieldException;
import performa.orm.ScheduledEmail;
import performa.orm.SentEmail;


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)
        {
            String          messageContent      =   scheduledEmail.getMessageContent();
            // replace tags
            
            TextDataSource  mesgBodyDataSource  =   new TextDataSource(messageContent);               
            String          toEmail             =   scheduledEmail.getJobApplication().getCandidate().getUser().getEmail();
            String          fromEmail           =   scheduledEmail.getJobApplication().getJob().getCreatedBy().getUser().getEmail();
            SentEmail       sentEmail           =   SentEmail.createSentEmail(ot);
            
            emailEngine.sendEmail(new String[] {toEmail}, fromEmail, scheduledEmail.getSubject() , new DataSource[]{mesgBodyDataSource});
            
            sentEmail.setSubject(scheduledEmail.getSubject());
            sentEmail.setSentDate(new Date());
            sentEmail.setApplicationStatus(scheduledEmail.getApplicationStatus());
            sentEmail.setMessageContent(messageContent);
            sentEmail.setEmailTo(toEmail);
            sentEmail.setJobApplication(scheduledEmail.getJobApplication());
                    
            scheduledEmail.delete();
        }
    }
    
    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        super.init(context);
        
        emailEngine = (Emailer) context.getSingleChild("EmailEngine");
    } 
}
