package com.ejie.y42b.utils;

import java.sql.SQLException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ejie.y42b.constantes.Y42bAgendaConstantes;
import com.ejie.y42b.model.Adjunto;
import com.ejie.y42b.utils.beans.MailItemBean;

/**
 * 
 *  
 * 
 */
public class Y42bSendMail {

	private static final Logger logger = LoggerFactory
			.getLogger(Y42bSendMail.class);

	/**
	 * 
	 * @param item
	 *            MailItemBean
	 * @throws MessagingException
	 *             MessagingException
	 */
	public void sendItem(MailItemBean item) throws MessagingException {

		Properties prop = Y42bUtils
				.loadProperties(Y42bAgendaConstantes.CONFIG_PATH);
		/*
		 * //Datos de cuenta de correo -Tomar del fichero properties String
		 * host=prop.getProperty("mail_host"); String
		 * fromAddress=prop.getProperty("mail_fromAddress"); int port =
		 * Integer.parseInt(prop.getProperty("mail_port"));
		 * 
		 * final String username=prop.getProperty("mail_username"); final String
		 * password=prop.getProperty("mail_password");
		 * 
		 * Properties props = new Properties(); props.put("mail.smtp.host",
		 * host); props.put("mail.smtp.auth", "true");
		 * props.put("mail.smtp.socketFactory.port", port);
		 * //props.put("mail.smtp.socketFactory.class", //
		 * "javax.net.ssl.SSLSocketFactory");
		 * props.put("mail.smtp.starttls.enable", "true");
		 * props.put("mail.smtp.port", port);
		 * 
		 * Session session = Session.getDefaultInstance(props, new
		 * javax.mail.Authenticator() { protected PasswordAuthentication
		 * getPasswordAuthentication() { return new
		 * PasswordAuthentication(username,password); } });
		 */
		String local = (String) prop.getProperty("y42bVistaWar.entorno.local");
		Session session = null;
		String fromAddress = prop.getProperty("mail_fromAddress");
		/*
		 * String host=""; int port = 0;
		 */
		final String username;
		final String password;

		if ("true".equals(local)) {
			Properties props = new Properties();
			username = prop.getProperty("y42bVistaWar.mail.local.username");
			password = prop.getProperty("y42bVistaWar.mail.local.password");
			/*
			 * host=(String) prop.getProperty("y42bVistaWar.mail.local.smtp");
			 * port = Integer.parseInt((String)
			 * prop.getProperty("y42bVistaWar.mail.local.port"));
			 */
			props.put("mail.smtp.host",
					(String) prop.getProperty("y42bVistaWar.mail.local.smtp"));
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.port",
					(String) prop.getProperty("y42bVistaWar.mail.local.port"));

			try {
				session = Session.getInstance(props,
						new javax.mail.Authenticator() {
							protected PasswordAuthentication getPasswordAuthentication() {
								return new PasswordAuthentication(username,
										password);
							}
						});

			} catch (Exception e) {
				Y42bSendMail.logger.error("Problema en adjunto "
						+ e.getMessage());
				// e.printStackTrace();
			}

		} else {
			/*
			 * username = prop.getProperty("y42bVistaWar.mail.local.username");
			 * password = prop.getProperty("y42bVistaWar.mail.local.password");
			 * host=(String) prop.getProperty("y42bVistaWar.mail.ejie.smtp");
			 * port = Integer.parseInt((String)
			 * prop.getProperty("y42bVistaWar.mail.local.port"));
			 */
			Properties props = new Properties();
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host",
					(String) prop.getProperty("y42bVistaWar.mail.ejie.smtp"));
			session = Session.getInstance(props);

		}

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(fromAddress));
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(item.getDestinatario()));
		message.setSubject(item.getAsunto());

		// Create the message part
		BodyPart messageBodyPart = new MimeBodyPart();

		// Fill the message
		messageBodyPart.setContent(item.getMensaje(),
				"text/html; charset=ISO8859_1");

		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);
		if (item.getAdjuntos() != null) {
			// Part two is attachment
			ByteArrayDataSource ds = null;
			DataHandler dh = null;

			for (Adjunto adjunto : item.getAdjuntos()) {

				try {
					byte[] raw = null;
					if (adjunto.getAdjunto() != null) {
						raw = adjunto.getAdjunto().getBytes(1,
								(int) adjunto.getAdjunto().length());
						ds = new ByteArrayDataSource(raw,
								adjunto.getContentType());// NOPMD 2012/02/29
															// (IDA)
						dh = new DataHandler(ds);// NOPMD 2012/02/29 (IDA)

						messageBodyPart = new MimeBodyPart();// NOPMD 2012/02/29
																// (IDA)
						messageBodyPart.setDataHandler(dh);
						messageBodyPart.setFileName(adjunto.getNombre());
						multipart.addBodyPart(messageBodyPart);
					}

				} catch (SQLException e) {
					Y42bSendMail.logger.error("Problema en adjunto "
							+ e.getMessage());
					// e.printStackTrace();
				}
			}
		}

		// Put parts in message
		message.setContent(multipart);

		// Transport transport = session.getTransport("smtp");
		// transport.connect(host, port, username, password);
		Transport.send(message);

		Y42bSendMail.logger.info("Correo enviado con exito!!");

	}

}
