/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

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 );
			}
		}
	}
	
