package com.ffii.lioner.modules.common.mail.service;

import java.util.Properties;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import com.ffii.lioner.modules.common.MailSMTP;
import com.ffii.lioner.modules.settings.service.SettingsService;

/** caching mail sender if config no changed */
@Service
public class MailSenderService {

  private SettingsService settingsService;

  private JavaMailSender sender;
  private MailSMTP mailConfigCachs;

	private Boolean ldapWebServiceRequired;
  
  public MailSenderService(SettingsService settingsService) {
    this.settingsService = settingsService;
  }

  public JavaMailSender get() {
    MailSMTP config = new MailSMTP(settingsService);
    if (this.sender == null || mailConfigCachs == null || !config.equals(this.mailConfigCachs)) {
      this.mailConfigCachs = config;
      JavaMailSenderImpl sender = new JavaMailSenderImpl();

      Properties props = new Properties();
      if(!ldapWebServiceRequired){
        props.put("mail.smtp.timeout", "20000");
        props.put("mail.smtp.connectiontimeout", "10000");
      }
      props.put("mail.smtp.auth", config.getAuth());
      props.put("mail.smtp.starttls.enable", "true");

      
      sender.setHost(config.getHost());
      sender.setPort(config.getPort());
      if(!ldapWebServiceRequired){
        sender.setUsername(config.getUsername());
        sender.setPassword(config.getPassword());
      }
      sender.setJavaMailProperties(props);

      this.sender = sender;
    }

    return this.sender;
  }
}
