package com.ejie.u74a.configuration;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * Configuración para el envío de emails
 * 
 *  
 * 
 */
@Configuration()
@PropertySource(value = "classpath:u74a/u74a.properties")
public class MailConfiguration {

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

	@Value(value = "${email.host}")
	private String host;

	@Value(value = "${email.port}")
	private String port;

	@Value(value = "${email.username}")
	private String username;

	@Value(value = "${email.password}")
	private String password;

	@Value(value = "${email.from}")
	private String from;

	@Value(value = "${email.subject}")
	private String subject;

	/**
	 * Java mail service.
	 * 
	 * @return java mail sender
	 */
	@Bean()
	public JavaMailSender javaMailService() {
		logger.debug("Datos mail: host - {}, port - {}, username - {}", this.host, this.port, this.username);

		JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
		javaMailSender.setHost(this.host);
		javaMailSender.setPort(Integer.valueOf(this.port));

		Properties mailProperties = new Properties();

		if (this.username != null && !"".equals(this.username)) {
			// Para Gmail (local)
			javaMailSender.setUsername(this.username);
			javaMailSender.setPassword(this.password);

			mailProperties.put("mail.smtp.auth", "true");
			mailProperties.put("mail.smtp.starttls.enable", "true");
		} else {
			// Para EJIE
			mailProperties.put("mail.smtp.auth", "false");
		}

		javaMailSender.setJavaMailProperties(mailProperties);

		return javaMailSender;
	}

	/**
	 * Simple mail message.
	 * 
	 * @return simple mail message
	 */
	@Bean()
	public SimpleMailMessage simpleMailMessage() {
		logger.debug("Datos mail: from - {}, subject - {}", this.from, this.subject);

		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom(this.from);
		simpleMailMessage.setSubject(this.subject);
		return simpleMailMessage;
	}

	// To resolve ${} in @Value
	/**
	 * Property config in dev.
	 * 
	 * @return property sources placeholder configurer
	 */
	@Bean()
	public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
		return new PropertySourcesPlaceholderConfigurer();
	}
}
