/*
 * 
 */
package com.fp.bpmlib.mail;

import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.fp.base.persistence.util.helper.GeneralDescriptions;
import com.fp.bpmlib.ejb.local.LogMailBeanLocal;
import com.fp.bpmlib.messages.MessageManager;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
import com.fp.mail.Mail;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.data.ThreadFacade;
import com.fp.persistence.pbpm.gene.TbpmGroups;
import com.fp.persistence.pbpm.gene.TbpmGroupsKey;

// TODO: Auto-generated Javadoc
/**
 * Class Mailer encargada del envío de Correos.
 * 
 * @author gfiallos
 */
public class Mailer {

    /** El valor de mail. */
    private Mail mail = null;

    /** El valor de request. */
    private final Request request;

    /**
     * Crea una nueva instancia de mailer.
     * 
     * @param pRequest the request
     * @throws Exception la exception
     */
    public Mailer(Request pRequest) throws Exception {
        request = pRequest;
        mail = new Mail(null, null, null, null, null, false);
        this.config();
    }

    /**
     * Config.
     * 
     * @throws Exception la exception
     */
    private void config() throws Exception {
    	System.out.println("---------------------------"+MailParameters.MAIL_SMTP_SERVER.getStringValue());
    	System.out.println("---------------------------"+ MailParameters.MAIL_SMTP_PORT.getIntValue());
        mail.config(MailParameters.MAIL_FROM.getStringValue(), MailParameters.MAIL_SMTP_SERVER.getStringValue(),
                MailParameters.MAIL_SMTP_PORT.getIntValue(), MailParameters.MAIL_SMTP_USER.getStringValue(),
                MailParameters.MAIL_SMTP_PASSWORD.getStringValue(), MailParameters.MAIL_SMTP_AUTH.isBooleanValue(),
                MailParameters.MAIL_SMTPS.isBooleanValue());
    }

    /**
     * Prepare message manager.
     * 
     * @param pTemplate the template
     * @return message manager
     * @throws Exception la exception
     */
    private MessageManager prepareMessageManager(Integer pTemplate) throws Exception {
        MessageManager m = new MessageManager(pTemplate, request.getLanguage(), null);
        m.setValue("request", request);
        return m;
    }

    /**
     * Fija el valor de subject.
     * 
     * @param pTemplate es el valor nuevo de subject
     * @throws Exception la exception
     */
    public void setSubject(Integer pTemplate) throws Exception {
        mail.setSubject(this.prepareMessageManager(pTemplate).getMessage());
    }

    /**
     * Fija el valor de content.
     * 
     * @param pTemplate es el valor nuevo de content
     * @throws Exception la exception
     */
    public void setContent(Integer pTemplate) throws Exception {
        mail.setCont(this.prepareMessageManager(pTemplate).getMessage());
    }

    /**
     * Fija el valor de to.
     * 
     * @param pRef es el valor nuevo de to
     * @throws Exception la exception
     */
    public void setTo(String pRef) throws Exception {
        String to = mail.getTo();
        if (to == null) {
            mail.setTo(pRef);
        } else {
            mail.setTo(to + "," + pRef);
        }
    }

    /**
     * Fija el valor de to user.
     * 
     * @param pUser es el valor nuevo de to user
     * @throws Exception la exception
     */
    public void setToUser(String pUser) throws Exception {
        this.setTo(GeneralDescriptions.getEmailByUser(pUser));
    }

    /**
     * Fija el valor de to group.
     * 
     * @param pGroup es el valor nuevo de to group
     * @throws Exception la exception
     */
    public void setToGroup(String pGroup) throws Exception {
        TbpmGroupsKey k = new TbpmGroupsKey(pGroup, ThreadFacade.getSessionData().getCompany());
        TbpmGroups g = TbpmGroups.find(PersistenceHelper.getEntityManager(), k);
        if (g == null) {
            throw new Exception("GRUPO NO EXISTE |" + pGroup + "|");
        }
        this.setTo(g.getEmail());
    }

    /**
     * Envía el Correo.
     * 
     * @throws Exception la exception
     */
    public void send() throws Exception {
    	try {
    		if ((mail.getTo() == null) || (mail.getSubject() == null) || (mail.getCont() == null)) {
    			throw new Exception(mail.getTo() + " " + mail.getSubject() + " " + (mail.getCont() != null));
    		}
    		String [] correosl=mail.getTo().split(",");
    		LogMailBeanLocal beanLocal  = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
    		for(String para:correosl){
    			try{
    				mail.setTo(para);
    				APPLogger.getLogger().info("Mensaje a enviar " + mail.getSubject() + " para " + mail.getTo());
    				mail.send();
    				try {
    					Map<String, Object> mapaMail = new HashMap<String, Object>();
    					mapaMail.put("to", mail.getTo());
    					mapaMail.put("subject", mail.getSubject());
    					mapaMail.put("cont", mail.getCont());
    					mapaMail.put("estado", "Y");
    					beanLocal.logMail(mapaMail);
    				} catch (Exception e) {
    					e.getMessage();
    					APPLogger.getLogger().error("1.-Excepcion en seteo mail");
    				}

    			}catch (Exception e) {
    				APPLogger.getLogger().warn("El mensaje" + mail.getSubject() + " para " + mail.getTo() + " no se ha podido enviar ");
    				APPLogger.getLogger().error(e, e);

    				try {
    					//LogMailBeanLocal beanLocal  = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
    					Map<String, Object> mapaMail = new HashMap<String, Object>();
    					mapaMail.put("to", mail.getTo());
    					mapaMail.put("subject", mail.getSubject());
    					mapaMail.put("cont", mail.getCont());
    					mapaMail.put("estado", "N");
    					mapaMail.put("error", e.getMessage());
    					beanLocal.logMail(mapaMail);
    				} catch (Exception e2) {
    					e.getMessage();
    					APPLogger.getLogger().error("2.-Excepcion en seteo mail");
    				}
    			}
    		}
    	}catch (NamingException e) {
    		e.getMessage();
    		APPLogger.getLogger().error("Servicio no encontrado");
    	}
    	catch (Exception e) {
    		e.getMessage();
    		APPLogger.getLogger().error("Excepcion al enviar mail");
    	}
    }
    
    /**
     * Envía el Correo.
     * 
     * @throws Exception la exception
     */
    public void sendWithAttachment() throws Exception {
    	try {
    		if ((mail.getTo() == null) || (mail.getSubject() == null) || (mail.getCont() == null)) {
    			throw new Exception(mail.getTo() + " " + mail.getSubject() + " " + (mail.getCont() != null));
    		}
    		String [] correosl=mail.getTo().split(",");
    		LogMailBeanLocal beanLocal  = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
    		for(String para:correosl){
    			try{
    				mail.setTo(para);
    				APPLogger.getLogger().info("Mensaje a enviar " + mail.getSubject() + " para " + mail.getTo());
    				mail.send();
    				try {
    					Map<String, Object> mapaMail = new HashMap<String, Object>();
    					mapaMail.put("to", mail.getTo());
    					mapaMail.put("subject", mail.getSubject());
    					mapaMail.put("cont", mail.getCont());
    					mapaMail.put("estado", "Y");
    					beanLocal.logMail(mapaMail);
    				} catch (Exception e) {
    					e.getMessage();
    					APPLogger.getLogger().error("1.-Excepcion en seteo mail");
    				}

    			}catch (Exception e) {
    				APPLogger.getLogger().warn("El mensaje" + mail.getSubject() + " para " + mail.getTo() + " no se ha podido enviar ");
    				APPLogger.getLogger().error(e, e);

    				try {
    					//LogMailBeanLocal beanLocal  = (LogMailBeanLocal) new InitialContext().lookup("java:global/maiaear-2.1/bpmlib/logMailBean");
    					Map<String, Object> mapaMail = new HashMap<String, Object>();
    					mapaMail.put("to", mail.getTo());
    					mapaMail.put("subject", mail.getSubject());
    					mapaMail.put("cont", mail.getCont());
    					mapaMail.put("estado", "N");
    					mapaMail.put("error", e.getMessage());
    					beanLocal.logMail(mapaMail);
    				} catch (Exception e2) {
    					e.getMessage();
    					APPLogger.getLogger().error("2.-Excepcion en seteo mail");
    				}
    			}
    		}
    	}catch (NamingException e) {
    		e.getMessage();
    		APPLogger.getLogger().error("Servicio no encontrado");
    	}
    	catch (Exception e) {
    		e.getMessage();
    		APPLogger.getLogger().error("Excepcion al enviar mail");
    	}
    }
    
}
