package com.ffii.fpsms.modules.common.mail.service

import com.ffii.fpsms.modules.common.MailSMTP
import com.ffii.fpsms.modules.settings.service.SettingsService
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.JavaMailSenderImpl
import org.springframework.stereotype.Service
import java.util.*

@Service
open class MailSenderService(private val settingsService: SettingsService) {
    private var sender: JavaMailSender? = null
    private var mailConfigCachs: MailSMTP? = null

    open fun get(): JavaMailSender {

        val config = MailSMTP(settingsService)

        if (this.sender == null || (mailConfigCachs == null) || !config.equals(this.mailConfigCachs)) {

            this.mailConfigCachs = config
            val sender = JavaMailSenderImpl()

            val props = Properties()
            val auth = config.auth ?: false
            if (auth) {
                props["mail.smtp.timeout"] = "20000"
                props["mail.smtp.connectiontimeout"] = "10000"
            }
            props["mail.smtp.auth"] = auth
//            The below setting needs to be included when the SMTP has TLS Version
//            props["mail.smtp.starttls.enable"] = "true"
//            props["mail.smtp.ssl.protocols"] = "TLSv1.2"

            sender.host = config.host
            sender.port = config.port!!
            if (auth) {
                sender.username = config.username
                sender.password = config.password
            }
            sender.javaMailProperties = props

            this.sender = sender
        }
        return this.sender ?: JavaMailSenderImpl()
    }
}