package org.seasar.jsf.runtime;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.seasar.framework.util.FileInputStreamUtil;
import org.seasar.framework.util.InputStreamUtil;
import org.seasar.jsf.TagProcessor;
import org.seasar.jsf.TagProcessorTreeFactory;
import org.seasar.jsf.ViewTemplate;
import org.seasar.jsf.ViewTemplateFactory;

/**
 * @author higa
 *  
 */
public class ViewTemplateFactoryImpl implements ViewTemplateFactory {

	private TagProcessorTreeFactory tagProcessorTreeFactory;

	private Map viewTemplates = new HashMap();

	public ViewTemplateFactoryImpl(
			TagProcessorTreeFactory tagProcessorTreeFactory) {

		this.tagProcessorTreeFactory = tagProcessorTreeFactory;
	}

	public synchronized ViewTemplate getViewTemplate(String realPath) {
		ViewTemplate template = (ViewTemplate) viewTemplates.get(realPath);
		if (template != null && !template.isModified()) {
			return template;
		}
		TagProcessor rootTagProcessor = null;
		File file = new File(realPath);
		InputStream is = new BufferedInputStream(FileInputStreamUtil
				.create(file));
		try {
			rootTagProcessor = tagProcessorTreeFactory
					.createTagProcessorTree(is);
		} finally {
			InputStreamUtil.close(is);
		}
		template = new ViewTemplateImpl(rootTagProcessor, file);
		viewTemplates.put(realPath, template);
		return template;
	}
}