package org.seasar.jsf.template.impl;

import java.io.File;

import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;

import org.seasar.jsf.template.ComponentFactory;
import org.seasar.jsf.template.ViewTemplate;

/**
 * @author higa
 *  
 */
public class ViewTemplateImpl implements ViewTemplate {

	private String viewId_;

	private ComponentFactory rootComponentFactory_;
	
	private File file_;
	
	private long lastModified_;

	public ViewTemplateImpl(String viewId, ComponentFactory rootComponentFactory, File file) {
		viewId_ = viewId;
		rootComponentFactory_ = rootComponentFactory;
		file_ = file;
		lastModified_ = file.lastModified();
	}

	public String getViewId() {
		return viewId_;
	}

	public ComponentFactory getRootComponentFactory() {
		return rootComponentFactory_;
	}

	public UIViewRoot createView() {
		UIViewRoot view = new UIViewRoot();
		view.setViewId(viewId_);
		appendChildComponent(view, rootComponentFactory_);
		return view;
	}

	protected void appendChildComponent(UIComponent parent,
			ComponentFactory childComponentFactory) {

		UIComponent child = childComponentFactory.createComponent();
		parent.getChildren().add(child);
		for (int i = 0; i < childComponentFactory.getChildCount(); ++i) {
			appendChildComponent(child, childComponentFactory.getChild(i));
		}
	}
	
	public boolean isModified() {
		return file_.lastModified() > lastModified_;
	}
}