//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010 huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE-----------------------------
package org.huihoo.workflow.script.compiler;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.huihoo.workflow.script.ScriptCompilationContext;
import org.huihoo.workflow.server.WorkflowContext;
import org.huihoo.workflow.xpdl.WorkflowCondition;
import org.huihoo.workflow.xpdl.condition.ScriptCondition;

public class ScriptCompiler extends Compiler
{
	private static Log log = LogFactory.getLog(ScriptCompiler.class);

	// ------------------------------------------------------------ Constructor
	public ScriptCompiler(ScriptCompilationContext ctxt)
	{
		super(ctxt);
	}

	// --------------------------------------------------------- Public Methods

	/**
	 * Determine if a compilation is necessary by checking the time stamp
	 * of the script page with that of the corresponding .class or .java file.
	 * 
	 * This method can by overidden by a subclasses of Compiler.
	 * @param checkClass If true, check against .class file,
	 *                   if false, check against .java file.
	 */
	public boolean isOutDated(boolean checkClass)
	{
		WorkflowContext templateContext = ctxt.getTemplateContext();
		if (templateContext.getRealPath("/") == null)
		{
			return false;
		}

		WorkflowCondition condition = ctxt.getWorkflowCondition();

		if (condition == null)
		{
			return false;
		}

		if (!(condition instanceof ScriptCondition))
		{
			return false;
		}

		long realLastModified = 0;

		String scriptFilePath = options.getScriptDir() + File.separator + condition.getContent();
		try
		{
			File scriptFile = new File(scriptFilePath);
			if (!scriptFile.exists())
			{
				return true;
			}

			realLastModified = scriptFile.lastModified();
		}
		catch (Exception e)
		{
			return true;
		}

		long targetLastModified = 0;
		File targetFile = null;

		if (checkClass)
		{
			targetFile = new File(ctxt.getScriptClassFileName());
		}
		else
		{
			targetFile = new File(ctxt.getScriptJavaFileName());
		}

		if (!targetFile.exists())
		{
			return true;
		}

		targetLastModified = targetFile.lastModified();

		if (targetLastModified < realLastModified)
		{
			return true;
		}

		return false;

	}
}
