package kr.co.jinwoosi.clfd.framework.mail;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;

@Service
public class MailService {

    @Value("${email.username}")
    private String emailUsername;
    @Value("${email.password}")
    private String emailPassword;
    @Value("${email.auth.home.url}")
    private String emailAuthHomeUrl;

    @Async("threadPoolTaskExecutor")
    public void gmailSend(String email, String subject, String text) {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "465"); //ssl로 보안설정(처음부터 암호화하여 보냄)
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailUsername, emailPassword);
            }
        });

        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(emailUsername));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(text);
            Transport.send(mimeMessage);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public String getLoginMailText(String userLoginId, String authCode) {
        StringBuffer sb = new StringBuffer();
        sb.append("해당 링크를 클릭하시면 회원가입이 완료됩니다.\n");
        sb.append(emailAuthHomeUrl).append("/clfd/join/auth.json?id=").append(userLoginId);
        sb.append("&authCode=").append(authCode);
        return sb.toString();
    }

    public String getFindIdText(List<String> loginIdList) {
        StringBuffer sb = new StringBuffer();
        sb.append("해당 이메일로 가입한 아이디 입니다.\n");
        loginIdList.forEach(s -> sb.append(s).append("\n"));
        return sb.toString();
    }

    public String getFindPasswordText(String tempPassword) {
        StringBuffer sb = new StringBuffer();
        sb.append("해당 아이디로 발급된 임시비밀번호 입니다.\n");
        sb.append(tempPassword + "\n");
        return sb.toString();
    }

    @Getter
    @AllArgsConstructor
    public enum EmailTitle {
        JOIN_AUTH("[컬러푸드] 회원인증"),
        FIND_ID("[컬러푸드] 아이디 찾기"),
        FIND_PW("[컬러푸드] 비밀번호 찾기");
        private String title;
    }
}
