/* ======================================================================
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.sqldatabase;

import org.bodington.server.*;

import java.io.File;
import java.util.Vector;
import java.util.Hashtable;

import org.apache.log4j.Logger;

/**
 * Describes the way an object of type SqlPersistentObject is stored
 * in an SQL database.  This class is used within the package only.
 * It is instantiated by an SqlDatabase object.
 * 
 * @author Jon Maber
 * @version 1
 */

// how to cope with fields that are arrays?
class SqlClass extends Object
	{

    private static Logger log = Logger.getLogger(SqlClass.class);
	/**
	 * Id in database for this type.
	 */
	int type;

	/**
	 * Id of super class of this class. Having a 0 signifies no super class in database.
	 */
	int super_type=0;

	/**
	 * Id of super class of this class. Having a 0 signifies no super class in database.
	 */
	SqlClass super_class=null;

	/**
	 * Database name - ignored at present.
	 */
	String db_name;

	/**
	 * Table where objects of this type are stored.
	 */
	String table_name;

	/**
	 * Name of java class for instantiating objects.
	 */
	String java_class;

	/**
	 * Optional loacl file system name of java archive file.
	 */
	String archive;

	/**
	 * Instance of java.lang.Class for java_class.
	 */

	private Class class_ref;

	/**
	 * Table of references to SqlClass objects representing subclasses
	 * keyed against type number.
	 */
	Hashtable sub_classes;

	/**
	 * Reference to field that contains the primary key.
	 */
	
	SqlField primary_key_field;

	/**
	 * The fields of the data type that will be synchronised with
	 * the SQL database keyed against field name.
	 */
	Hashtable fields;

	/**
	 * The fields stored in proper sequence.
	 */
	Vector fields_in_order;

	/**
	 * An SQL string for fetching a single instance from the database
	 * keyed by its primary key.
	 */
	
	String fetch_by_pk_sql=null;

	/**
	 * An SQL string for updating a single instance from the database
	 * keyed by its primary key.
	 */
	String update_by_pk_sql=null;

	/**
	 * An SQL string for inserting a single instance into the database.
	 */
	String insert_sql=null;

	/**
	 * An SQL string for inserting a single instance into the database.
	 */
	String delete_sql=null;

	/**
	 * Constructor initialises field lists.
	 */
	
	SqlClass()
		{
		sub_classes = new Hashtable();
		fields = new Hashtable();
		fields_in_order = new Vector();
		checked = 0;
		}


    private long checked;
    
    
    public Class getDataClass()
        {
        try
            {
            if ( archive == null )
		        {
		        if ( class_ref == null )
		            class_ref = Class.forName( java_class );
		        }
		    else
                {
                long now = System.currentTimeMillis();
                if ( class_ref == null || (now - checked) > 60000 )
                    {
                    checked = now;

			        ServerClassLoader loader = ServerClassLoader.getClassLoader( new File( archive ), this.getClass().getClassLoader() );
			        class_ref = loader.loadClass( java_class );
			        relinkMethods();
                    }
                }
			}
		catch ( Exception ex )
			{
			log.error( ex.getMessage(), ex );
			class_ref = null;
			}
            
        return class_ref;
        }


    public void relinkMethods()
        throws ClassNotFoundException, NoSuchMethodException
        {
        boolean primative;
        SqlField sqlfield;
		String[] primative_names= { "boolean", "char", "byte", "short", "int", "long", "float", "double", "void" };
		Class[] primative_classes= { Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, 
										Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE };
		//Class getp[] = new Class[1];
		Class setp[] = new Class[1];
        
		for ( int i=0; i< fields_in_order.size(); i++ )
			{
			sqlfield = (SqlField)fields_in_order.elementAt( i );
			if ( sqlfield.set_method_name!=null && sqlfield.set_java_class!=null )
				{
				primative=false;
				for ( int j=0; j<primative_names.length; j++ )
					{
					if ( sqlfield.set_java_class.equals( primative_names[j] ) )
						{
						primative=true;
						setp[0] = primative_classes[j];
						break;
						}
					}
				if ( !primative )
					setp[0] = Class.forName( sqlfield.set_java_class );
				//BuildingServer.codeTrace( "Looking for " + sqlfield.set_method_name + "( " + setp[0] + ")" );
				sqlfield.set_method = getDataClass().getMethod( sqlfield.set_method_name, setp );
				}
			if ( sqlfield.get_method_name!=null && sqlfield.get_java_class!=null )
				{
				sqlfield.get_method = getDataClass().getMethod( sqlfield.get_method_name, null );
				}
			}
        }
        
        
	void appendFields( StringBuffer buffer, SqlClass c )
		{
		SqlField sqlfield;
		for ( int i=0; i<c.fields_in_order.size(); i++ )
			{
			if ( buffer.length() > 7 )
				buffer.append( ", " );
			sqlfield=(SqlField)c.fields_in_order.elementAt( i );
			buffer.append( sqlfield.field );
			}
		}

	/**
	 * Constructs various SQL strings internally for use with
	 * SqlPersistentObject instances.
	 */

		
	void update()
		throws BuildingServerException
		{
		StringBuffer sql;
		SqlField sqlfield;
		
/*
		sql = new StringBuffer();
		sql.append( "SELECT " );
		
		if ( super_class!=null )
			appendFields( sql, super_class );
		appendFields( sql, this );
		
		sql.append( " FROM " );
		if ( super_class!=null )
			{
			sql.append( super_class.table_name );
			sql.append( ", " );
			}
		sql.append( table_name );
		sql.append( " WHERE " );
		if ( super_class!=null )
			{
			sql.append( super_class.primary_key_field.field );
			sql.append( " = " );
			sql.append( primary_key_field.field );
			sql.append( " AND " );
			}
		sql.append( primary_key_field.field );
		sql.append( " = " );
		
		fetch_by_pk_sql=sql.toString();
	*/

		if ( table_name !=null )
			{
			sql = new StringBuffer();
			sql.append( "UPDATE " );
			sql.append( table_name );
			sql.append( " SET " );
			int p=0;
			for ( int i=0; i<fields_in_order.size(); i++ )
				{
				sqlfield=(SqlField)fields_in_order.elementAt( i );
				
				if ( sqlfield == primary_key_field )
					continue;
				
				sql.append( sqlfield.field );
				sql.append( " = ? " );
				if ( (p+2) < fields_in_order.size() )
					sql.append( ", " );
				else
					sql.append( " " );
				p++;
				}
			sql.append( " WHERE " );
			sql.append( primary_key_field.field );
			sql.append( " = ?" );
			
			update_by_pk_sql=sql.toString();

		
			sql = new StringBuffer();
			sql.append( "INSERT INTO " );
			sql.append( table_name );
			sql.append( "( " );
			for ( int i=0; i<fields_in_order.size(); i++ )
				{
				sqlfield=(SqlField)fields_in_order.elementAt( i );
				
				sql.append( sqlfield.field );
				if ( (i+1) < fields_in_order.size() )
					sql.append( ", " );
				else
					sql.append( " " );
				}
			sql.append( ") VALUES ( " );
			for ( int i=0; i<(fields_in_order.size()-1); i++ )
				sql.append( "? , " );
			sql.append( "? )" );
			
			insert_sql=sql.toString();

			sql = new StringBuffer();
			sql.append( "DELETE FROM " );
			sql.append( table_name );
			sql.append( " WHERE " );
			sql.append( primary_key_field.field );
			sql.append( " = ?" );
			
			delete_sql=sql.toString();
			}
				
		}

	/**
	 * Debugging method for dumping state.
	 */
		
	void dump()
		{
		BuildingServer.codeTrace( "SqlClass.dump()" );
		BuildingServer.codeTrace( "type = " 		+ type );
		BuildingServer.codeTrace( "db_name = "		+ db_name );
		BuildingServer.codeTrace( "table_name = "	+ table_name );
		BuildingServer.codeTrace( "java_class = "	+ java_class );
		BuildingServer.codeTrace( "archive = "	    + archive );
		BuildingServer.codeTrace( "class_ref = "	+ class_ref );
		BuildingServer.codeTrace( "fields:" );

		SqlField field;
		for ( int i=0; i< fields_in_order.size(); i++ )
			{
			field=(SqlField)fields_in_order.elementAt( i );
			BuildingServer.codeTrace( "field " + i );
			BuildingServer.codeTrace( "field name " + field.field );
			BuildingServer.codeTrace( "set method name " + field.set_method_name );
			BuildingServer.codeTrace( "set java class " + field.set_java_class );
			BuildingServer.codeTrace( "get method name " + field.get_method_name );
			BuildingServer.codeTrace( "get java class " + field.get_java_class );
			}
		}
	}
	
