
package com.dla.dda.utils.email.client;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.dla.dda.domain.model.email.MessageAttachment;


/**
 * 
 * @see servicio para mandar correos utilizando un template
 * @author montieln
 * @version 1.0
 */
public class EmailService {
	private Logger logger = LoggerFactory.getLogger(EmailService.class);

	private JavaMailSenderImpl mailSender;
	private SimpleMailMessage templateMessage;

	private VelocityEngine velocityEngine;
	private String templatePath;

	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}

	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	public void setTemplateMessage(SimpleMailMessage templateMessage) {
		this.templateMessage = templateMessage;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	/**
	 * @author nmontielh
	 * @see Metodo para enviar un correo con un archivo adjunto
	 * @param messageAttachment
	 */
	
	public void sendMessage(Serializable emailModel, MessageAttachment messageAttachment) {

		logger.info("sending message [{}]", messageAttachment);

		MimeMessage message = mailSender.createMimeMessage();

		try {

			MimeMessageHelper helper = new MimeMessageHelper(message, true);

			// Se considera que estos valores ya estan previamente configurados
			if (messageAttachment.getFromAdddres() != null)
				helper.setFrom(messageAttachment.getFromAdddres());
			else
				helper.setFrom(templateMessage.getFrom());

			// Seteamos el subject
			if (messageAttachment.getSubject() != null)
				helper.setSubject(messageAttachment.getSubject());
			else
				helper.setSubject(templateMessage.getSubject());

			// Creamos y seteamos el cuerpo del correo
			String texto = createText(emailModel);
			helper.setText(texto, true);

			// Validamos la lista de distribucion a quien va dirigido
			if (messageAttachment.getToAddres() != null && messageAttachment.getToAddres().length > 0)
				helper.setTo(messageAttachment.getToAddres());
			else
				helper.setTo(templateMessage.getTo());

			// Validamos si el archivo adjunto existe para enviarlo, de lo
			// contrario se va vacio
			if (messageAttachment.getAttachmentFilename() != null && messageAttachment.getIos() != null
					&& messageAttachment.getContentType() != null)
				helper.addAttachment(messageAttachment.getAttachmentFilename(), messageAttachment.getIos(),
						messageAttachment.getContentType());

			
			Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
			
			MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
			mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
			mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
			mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
			mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
			mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822"); 
			
			mailSender.send(message);

		} catch (MessagingException e) {
			logger.error("hubo un error al enviar el correo:" + e.getMessage(), e);
		}

	}

	/**
	 * @see crea el texto del correo con base a un template
	 * @param messageAttachment
	 * @return
	 */

	@SuppressWarnings("deprecation")
	private String createText(Serializable emailModel) {

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("emailModel", emailModel);

		String texto = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);

		return texto;
	}
	

}
