package performa.ws;

import java.io.IOException;
import java.util.*;
import oneit.appservices.config.ConfigMgr;
import oneit.appservices.ws.*;
import oneit.appservices.ws.services.ORMUpdateJSONService;
import oneit.email.*;
import oneit.logging.*;
import oneit.net.LoopbackHTTP;
import oneit.objstore.*;
import oneit.servlets.jsp.ui.DefaultUICustomiser;
import oneit.utils.*;
import oneit.utils.transform.MapTransform;
import oneit.utils.transform.param.*;
import org.json.*;
import performa.orm.*;
import performa.orm.types.SentVia;
import performa.utils.*;

/**
 *
 * @author chamathkalhara
 */
public class SendMessage extends ORMUpdateJSONService
{
    public  static final LoggingArea    LOG                     =   LoggingArea.createLoggingArea("SendMessageLog");
    protected ConfigurableEmailer       APP_MESSAGE_EMAILER     =   (ConfigurableEmailer) ConfigMgr.getConfigObject(ConfigMgr.GLOBAL_CONFIG_SYSTEM, "AppMessageEmailer");
    protected ConfigurableEmailer       APP_EMAIL_EMAILER       =   (ConfigurableEmailer) ConfigMgr.getConfigObject(ConfigMgr.GLOBAL_CONFIG_SYSTEM, "AppEmailEmailer");
    PrefixCompoundTransform             prefixTransform         =   new PrefixCompoundTransform();
    
    @Override
    public void processForm(JSONServiceRequest request, ObjectTransaction objTran, JSONObject result, MultiException exceptions, Set<BaseBusinessClass> createdBBCs, Set<BaseBusinessClass> updatedBBCs) throws BusinessException, JSONException
    {
        List<Message>   createdMessages       = WSUtils.filterBBCs(Message.REFERENCE_Message, createdBBCs);
        List<Message>   updatedMessages       = WSUtils.filterBBCs(Message.REFERENCE_Message, updatedBBCs);
        List<Message>   allMessages           = new ArrayList(createdMessages);
        
        allMessages.addAll(updatedMessages);
        
        for (Message message : allMessages)
        {
            if (message.getStatus() != ObjectStatus.NEW)
            {
                LogMgr.log(LOG, LogLevel.PROCESSING1, "Message should be a new one");
                break;
            }
            ConfigurableEmailer       EMAILER = null;
            
            if (message.getSentVia() == SentVia.EMAIL)
            {
                EMAILER = APP_EMAIL_EMAILER;
            }
            if (message.getSentVia() == SentVia.ON_APP)
            {
                EMAILER = APP_MESSAGE_EMAILER;
            }
            
            JobApplication      jobApplication      = message.getJobApplication();
            
            
            
            String              appUrl              = getShortantURL(jobApplication.getID().longValue());
            Candidate           candidate           = jobApplication.getCandidate();
            HiringTeam          hiringTeam          = jobApplication.getJob().getHiringTeam();
            ObjectTransform     defaultTransform    = new MapTransform(CollectionUtils.mapEntry("link", appUrl).toMap());
            
            prefixTransform.add(message.getClass().getSimpleName(), new ORMPipelineTransform(message));
            prefixTransform.add(candidate.getUser().getClass().getSimpleName(), new ORMPipelineTransform(candidate.getUser()));
            prefixTransform.add(hiringTeam.getClass().getSimpleName(), new ORMPipelineTransform(hiringTeam));
            prefixTransform.setDefault(defaultTransform);
            
            if (message.getSentVia() == SentVia.EMAIL || message.getSentVia() == SentVia.ON_APP)
            {
                try
                {
                    EMAILER.sendTransactionalEmail(objTran,
                            new Date(),
                            prefixTransform,
                            new String[]{candidate.getUser().getEmail()},
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            candidate.getID().longValue());
                }
                catch (ConfigurableEmailerException ex)
                {
                    LogMgr.log(LOG, LogLevel.PROCESSING1, "Error when sending the mail to " + candidate.getUser().getEmail() , ex);
                }
            }
            else
            {
                SMSUtils    smsUtils    = (SMSUtils) ConfigMgr.getConfigObject("CONFIG.CUSTOM", "SMS");
                String      smsContent  = MessagingUtils.getArticleContent(objTran, "AppSMSMessageTemplate");
        
                if (smsContent == null)
                {
                    LogMgr.log(LOG, LogLevel.PROCESSING1, "Ignore sending SMS. smsContent is null ", this);
                    return;
                }
                
                smsContent = StringUtils.replaceParams (StringUtils.fromHTML(smsContent), prefixTransform);

                try
                {
                    smsUtils.sendSMS(smsContent, candidate.getPhone(), null, LOG);
                    LogMgr.log(LOG, LogLevel.PROCESSING1, "SMS sent to ", candidate.getPhone(), this);
                }
                catch (IOException ex)
                {
                    LogMgr.log(LOG, LogLevel.PROCESSING1, ex, "Error while sending AppSMSMessageTemplate");
                    throw new BusinessException("Error while sending SMS");
                }
            }
        }
        
        super.processForm(request, objTran, result, exceptions, createdBBCs, updatedBBCs);
    }
    
    private String getShortantURL(Long jobAppID)
    {
        String url = LoopbackHTTP.getRemoteAccessURL(DefaultUICustomiser.ANGULAR_BASE_PATH + "/message-engine/" + jobAppID);
        
        return url;
    }
}