package de.hsadmin.core.qserv;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import net.sf.jtpl.Template;

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

public class MailerProcessor extends AbstractProcessor {

	private static final long serialVersionUID = 1L;

	private String aTo;
	private String aSubject;
	private String aBody;

	public MailerProcessor(String aTo, String aSubject, String aBody) {
		this.aTo = aTo;
		this.aSubject = aSubject;
		this.aBody = aBody;
	}

	public MailerProcessor(String aTo, String aSubject, String templateName, Map<String, String> templateValues) throws ProcessorException {
		this.aTo = aTo;
		this.aSubject = aSubject;
		try {
			InputStream stream = MailerProcessor.class.getClassLoader().getResourceAsStream(templateName);
			Template template = new Template(new InputStreamReader(stream));
			for (String key : templateValues.keySet()) {
				template.assign(key, templateValues.get(key));
			}
			template.parse("main");
			this.aBody = template.out();
		} catch (IllegalArgumentException e) {
			throw new ProcessorException(e);
		} catch (IOException e) {
			throw new ProcessorException(e);
		}
	}

	public Object process() throws ProcessorException {
		try {
			Config config = Config.getInstance();
			String aFrom = config.getProperty("hsadmin.smtp.from", "unconfigured_from@example.com");
			String aCC = config.getProperty("hsadmin.smtp.cc", "unconfigured_cc@example.com");
			SmtpHelper.send(aFrom, aTo, aCC, aSubject, aBody);
			return null;
		} catch (HSAdminException e) {
			throw new ProcessorException(e);
		}
	}
}
