package dev.peerat.backend.utils;

import java.util.Date;
import java.util.Properties;

import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

public class Mail {
	private Session session;
	private String fromAddress;
	
	public Mail(String initUsername, String initPassword, String initSmtpHost, int initSmtpPort, String initFromAddress) {
		System.out.println("login on "+initUsername+" into "+initSmtpHost+":"+initSmtpPort);
		Properties props = new Properties();
		props.put("mail.smtp.host", initSmtpHost);
		props.put("mail.smtp.port", initSmtpPort);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		
		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(initUsername, initPassword);
			}
		};
		session = Session.getInstance(props, auth);
		fromAddress = initFromAddress;
	}
	
    public void send(String toAddress, String subject, String text){
    	try
	    {
	      MimeMessage msg = new MimeMessage(session);
	      //set message headers
	      msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
	      msg.addHeader("format", "flowed");
	      msg.addHeader("Content-Transfer-Encoding", "8bit");

	      msg.setFrom(new InternetAddress(fromAddress, "Peer-at Code"));
	      msg.setReplyTo(InternetAddress.parse(fromAddress, false));
	      msg.setSubject(subject, "UTF-8");
	      msg.setText(text, "UTF-8");
	      msg.setSentDate(new Date());

	      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress, false));
	      Transport.send(msg);
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
    }
}
