/* ======================================================================
The Bodington System Software License, Version 1.0
 
Copyright (c) 2001 The University of Leeds.  All rights reserved.
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
 
1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
 
2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.
 
4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.
 
5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.
 
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
=========================================================
 
This software was originally created by the University of Leeds and may contain voluntary
contributions from others.  For more information on the Bodington Open Source Project, please
see http://bodington.org/
 
====================================================================== */

package org.bodington.servlet.template;

import java.util.logging.*;



import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.bodington.server.BuildingContext;
import org.bodington.database.PrimaryKey;


public class Template
{
    private File       file;
    
    private String    facility;
    private Integer    style;
    private String     name;
    private String	  url;
    private PrimaryKey resource_id;
    
    private XmlTemplate xml_template;
    private String class_name;

    private GifTemplate gif_template;
    
    
    private boolean redirected=false;
    private long file_timestamp;
    private long template_timestamp;
    
    private static String class_path, template_dir, class_dir;
    private static Hashtable by_resource_id=new Hashtable();
    private static Hashtable by_style=new Hashtable();
    //public static Integer one = new Integer( 1 );
    private static Integer minus_one = new Integer( -1 );
    
    
    
    public static Template get( String f, Integer style, PrimaryKey r, String n )
    {
	Template t;
	
	
	if ( r!=null )
	{
	    t = privateGet( f, style, r, n );
	    if ( t!=null )
		return t;
	    // if a specific resource was specified and not found try
	    // checking with null resource
	    // (this one is done recuresively to apply other rules
	    
	    return get( f, style, null, n );
	}
	
	if ( style!=null )
	{
	    t = privateGet( f, style, null, n );
	    if ( t!=null )
		return t;
	    
	    if ( !f.equals( "default" ) )
	    {
		t = privateGet( "default", style, null, n );
		if ( t!=null )
		    return t;
	    }
	    
	    // didn't find file within style so check default style
	    // can do this recursively
	    return get( f, null, null, n );
	}
	
	// no resource or style specified so check default style
	// if not found by resource, style or facility try the
	
	t = privateGet( f, null, null, n );
	if ( t!=null )
	    return t;
	
	if ( !f.equals( "default" ) )
	    t = privateGet( "default", null, null, n );
	
	return t;
    }
    
    private static Template privateGet( String f, Integer style, PrimaryKey r, String n )
    {
	Hashtable templates;
	Hashtable by_facility;
	Template t;
	StringBuffer file_name;
	StringBuffer cname;
	StringBuffer url;
	File file;
	long now;
	Long key = null;
	
	//search for template by resource if specified
	if ( r!=null )
	{
	    templates = (Hashtable)by_resource_id.get( r );
	    if ( templates == null )
	    {
		templates = new Hashtable();
		by_resource_id.put( r, templates );
	    }
	}
	else
	{
	    // resource not specified so select style set and then
	    // look in there by facility
	    // -1 used for null style set.
	    
	    if ( style==null )
		style = minus_one;
	    
	    by_facility = (Hashtable)by_style.get( style );
	    if ( by_facility==null )
	    {
		by_facility = new Hashtable();
		by_style.put( style, by_facility );
	    }
	    
	    
	    templates = (Hashtable)by_facility.get( f );
	    if ( templates == null )
	    {
		templates = new Hashtable();
		by_facility.put( f, templates );
	    }
	}
	
	t = (Template)templates.get( n );
	//always create a template object even if there isn't a file
	if ( t==null )
	{
	    file_name = new StringBuffer();
	    cname = new StringBuffer();
	    cname.append( "working." );
	    url = new StringBuffer();
	    url.append( "/" );
	    //file_name.append( BuildingContext.getContext().getProperty( "buildingservlet.templatedirectory" ) );
	    if ( r!=null )
	    {
		file_name.append( "res_" );
		file_name.append( r.toString() );
		file_name.append( "/" );
		cname.append( "res_" );
		cname.append( r.toString() );
	    }
	    else
	    {
		file_name.append( "style_" );
		if ( style.equals( minus_one ) )
		    file_name.append( "default" );
		else
		    file_name.append( style.toString() );
		file_name.append( "/" );
		
		file_name.append( f );
		file_name.append( "/" );
		cname.append( "style_" );
		if ( style.equals( minus_one ) )
		    cname.append( "default" );
		else
		    cname.append( style.toString() );
		cname.append( "_" );
		
		cname.append( f );
	    }
	    
	    file_name.append( n );
	    url.append( file_name.toString() );
	    
	    cname.append( ".template_" );
	    cname.append( n.substring( 0, n.indexOf( '.' ) ) );
	    
	    Logger.getLogger( "org.bodington" ).finer( file_name.toString() );
	    Logger.getLogger( "org.bodington" ).finer( url.toString() );
	    file = new File(
	    getTemplateDirectory(),
	    file_name.toString()
	    );
	    t = new Template( file, url.toString(), cname.toString().replace( '-', '_' ), f, style, r, n );
	    templates.put( n, t );
	}
	
	if ( t.exists() )
	    return t;
	
	//forget it there isn't a template file.
	return null;
    }
    
    public static void setClassPath( String str )
    {
	class_path = str;
    }
    
    public static String getClassPath()
    {
	if ( class_path == null )
	    class_path = System.getProperty( "java.class.path" );
	
	return class_path;
    }
    
    public static void setTemplateDirectory( String str )
    {
	template_dir = str;
    }
    
    public static String getTemplateDirectory()
    {
	return template_dir;
    }
    
    public static void setClassDirectory( String str )
    {
	class_dir = str;
    }
    
    public static String getClassDirectory()
    {
	return class_dir;
    }
    
    public Template( File f, String url, String cname, String fac, Integer s, PrimaryKey res, String n )
    {
	file=f;
	facility = fac;
	style = s;
	resource_id = res;
	name = n;
	this.class_name = cname;
	this.url = url;
	
	redirected = !name.toLowerCase().endsWith( ".html" ) && !name.toLowerCase().endsWith( ".gif" );
	file_timestamp = file.lastModified();
        template_timestamp = System.currentTimeMillis();
        
	if ( !redirected )
	{
	    if ( name.toLowerCase().endsWith( ".gif" ) )
	    {
		gif_template = new GifTemplate();
	    }
	    else
	    {
		File class_dir_file = new File( getClassDirectory() );
		xml_template = new XmlTemplate( f, class_dir_file, class_name, getClassPath()  );
	    }
	}
    }
    
    public boolean exists()
    {
	return (file.exists() && file.isFile() );
    }
    
    public boolean isRedirected()
    {
	return redirected;
    }
    
    public String getUrl()
    {
	return url;
    }
    
    public File getFile()
    {
        return file;
    }
 
    public long getTemplateTimestamp()
    {
        long current_file_timestamp = file.lastModified();
        if ( current_file_timestamp != file_timestamp )
        {
            template_timestamp = System.currentTimeMillis();
            file_timestamp = current_file_timestamp;
        }
        return template_timestamp;
    }
    
    public XmlTemplateProcessor getXmlTemplateProcessor()
    {
	if ( xml_template != null )
	    return xml_template.getProcessor();
	
	if ( gif_template != null )
	    return gif_template.getProcessor();
	
        return null;
    }
    
 
        
}
