package de.hsadmin.core.qserv;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import net.sf.jtpl.Template;

public class TemplateProcessor extends AbstractProcessor {

	private static final long serialVersionUID = 4520635523274792876L;

	private String content = null;
	private String targetPath = null;
	private boolean overwriteTarget = false; 
	
	public TemplateProcessor(String templateName, Map<String, String> templateValues, String targetPath, boolean overwriteTarget) throws ProcessorException {
		this.targetPath = targetPath;
		this.overwriteTarget = overwriteTarget;
		try {
			InputStream stream = TemplateProcessor.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");
			content = template.out();
		} catch (IOException e) {
			throw new ProcessorException(e);
		}
	}
	
	@Override
	public Object process() throws ProcessorException {
		try {
			File file = new File(targetPath);
			if (file.exists() && !overwriteTarget) {
				return null;
			}
			if (!file.exists() || file.canWrite()) {
				BufferedWriter writer = new BufferedWriter(new FileWriter(file));
				writer.append(content);
				writer.close();
			} else {
				throw new ProcessorException("could not write file " + targetPath);
			}
			return null;
		} catch (IOException e) {
			throw new ProcessorException(e);
		}
	}

}
