package de.hsadmin.core.qserv;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;

import de.hsadmin.core.model.HSAdminException;
import de.hsadmin.core.util.Config;

public class SmtpHelper {

	public static void send(String fromAddress, String toAddress, String subject, String text) 
			throws HSAdminException {
		send(fromAddress, toAddress, null, subject, text);
	}
	
	public static void send(String fromAddress, String toAddress, String ccAddress, String subject, String text) 
			throws HSAdminException {
		try {
			SMTPClient client = new SMTPClient();
			String canonicalHostName = InetAddress.getLocalHost().getHostName();
			String smtpHost = Config.getInstance().getProperty("smtp.host");
			if (smtpHost == null || smtpHost.trim().isEmpty()) {
				smtpHost = "localhost";
			}
			if ("unittest".equals(smtpHost)) { // Nur fuer Unit-Tests
				if (subject.toLowerCase().contains("error")) {
					throw new HSAdminException("Konnte Mail nicht senden");
				}
				System.out.println("------------------------");
				System.out.println("From: " + fromAddress);
				System.out.println("To: " + toAddress);
				System.out.println("Subject: " + subject);
				System.out.println("\n" + text);
				return;
			}
			client.connect(smtpHost, 25);
			int reply = client.getReplyCode();
			if (!SMTPReply.isPositiveCompletion(reply)) {
				throw new HSAdminException("Konnte Mail Server nicht erreichen");
			}
			client.login(canonicalHostName);
			client.setSender(fromAddress.trim());
			client.addRecipient(toAddress.trim());
			if (ccAddress != null && ccAddress.trim().length() > 3) {
				client.addRecipient(ccAddress.trim());
			}
			Writer sendMessageData = client.sendMessageData();
			if (sendMessageData == null) {
				throw new HSAdminException("Konnte Mail nicht senden (SMTP-Relay-Problem)");
			}
			PrintWriter wr = new PrintWriter(sendMessageData);
			SimpleSMTPHeader header = new SimpleSMTPHeader(fromAddress, toAddress,
					subject);
			wr.write(header.toString());
			wr.write(text);
			wr.close();
			if (!client.completePendingCommand()) {
				throw new HSAdminException("Konnte Mail nicht senden");
			}
			client.logout();
			client.disconnect();
		} catch (UnknownHostException e) {
			throw new HSAdminException(e);
		} catch (SocketException e) {
			throw new HSAdminException(e);
		} catch (IOException e) {
			throw new HSAdminException(e);
		}
	}

}
