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

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.apache.log4j.Logger;



import org.bodington.database.*;
import org.bodington.pool.ObjectPoolException;
import org.bodington.server.realm.*;
import org.bodington.server.resources.*;
import org.bodington.text.*;

import java.lang.reflect.*;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Calendar;

public class JobScheduler extends java.lang.Thread
    {
    private static Logger log = Logger.getLogger(JobScheduler.class);
    private static JobScheduler the_instance;


    private boolean run = true;
    private boolean started=false;
    private boolean stopped=false;
    
    public String error;

    public int pause = 30*1000;  // thirty seconds worth of milliseconds
    
    public static JobScheduler getJobScheduler( boolean create )
        {
        if ( the_instance == null && create )
            the_instance = new JobScheduler();
        return the_instance;
        }
        
    private JobScheduler()
        {
        super("Job Scheduler");
        error=null;
        this.start();
        
        synchronized( this )
            {
            for ( int i=0; !started && !stopped && i<30; i++  )
                {
                try
                    {
                    this.wait( 10000 );
                    }
                catch ( InterruptedException iex )
                    {
                    }
                }
            }
        }


    public void deleteJob( Job job )
        throws BuildingServerException
	{
	Enumeration enumeration = JobResult.findJobResults( "job_id = " + job.getJobId() );
	JobResult job_result;
	while ( enumeration.hasMoreElements() )
	    {
	    job_result = (JobResult)enumeration.nextElement();
	    job_result.delete();
	    }
	job.delete();
	}
	
    public void addJob( String session_name, String method_name, String parameter )
        throws BuildingServerException
        {
        addJob( session_name, method_name, parameter, Job.REPEAT_TYPE_ONCE );
        }

    public void addJob( String session_name, String method_name, String parameter, int repeat_type)
    	throws BuildingServerException
    {
    	 addJob( session_name, method_name, parameter, repeat_type , Calendar.getInstance());
    }
    
    public void addJob( String session_name, String method_name, String parameter, int repeat_type, Calendar from)
        throws BuildingServerException
        {
	int i;
        User user = (User)BuildingContext.getContext().getUser();
        Resource resource = BuildingContext.getContext().getResource();
        
        /*
        if ( user == null || !user.getUserId().equals( user_id ) )
            throw new BuildingServerException( "Only sysadmin can add jobs to scheduler." );
        */
            
        Job j = new Job();
        j.setUserId( user.getUserId() );
        j.setResourceId( resource.getResourceId() );
        j.setSessionName( session_name );
        j.setMethodName( method_name );
        j.setParameter( parameter );
        j.setState( Job.STATE_OVERDUE );
        j.setSubmissionTime( new java.sql.Timestamp( System.currentTimeMillis() )       );
        j.setFromTime( new java.sql.Timestamp( from.getTimeInMillis())       );
        j.setToTime( null );
	j.setRepeatSpec( 0 );
	
	Calendar cal = Calendar.getInstance();
	cal.setTime( j.getFromTime() );
	
	switch ( repeat_type )
	    {
	    case Job.REPEAT_TYPE_DAILY:
		j.setRepeatType( Job.REPEAT_TYPE_DAILY );
		break;
	    case Job.REPEAT_TYPE_WEEKLY:
		j.setRepeatType( Job.REPEAT_TYPE_WEEKLY );
		j.setRepeatSpecDayOfWeek( cal.get( Calendar.DAY_OF_WEEK ), true );
		break;
	    case Job.REPEAT_TYPE_MONTHLY_DAY:
		j.setRepeatType( Job.REPEAT_TYPE_MONTHLY_DAY );
		j.setRepeatSpecDayOfMonth( cal.get( Calendar.DATE ) );
		for ( i=Calendar.JANUARY; i<= Calendar.DECEMBER; i++ )
		    j.setRepeatSpecMonthOfYear( i, true );
		break;
	    case Job.REPEAT_TYPE_MONTHLY_WEEK:
		j.setRepeatType( Job.REPEAT_TYPE_MONTHLY_WEEK );
		j.setRepeatSpecWeekOfMonth( 1, Calendar.MONDAY, true );
		for ( i=Calendar.JANUARY; i<= Calendar.DECEMBER; i++ )
		    j.setRepeatSpecMonthOfYear( i, true );
		break;
	    default:
		j.setRepeatType( Job.REPEAT_TYPE_ONCE );
		break;
	    }
	    
        j.setRepeatPeriod( 1 );
	j.setFirstExecutionTime();
        j.save();
        }
    
    /**
     * Look for jobs that match the supplied parameters. None of the parameters
     * should be null although they may be empty strings. Dont ask me why (database).
     * This might have been a nice method if it wasn't for the SQL hell.
     * @param session The session to look for. Normally this is the full (including package) class name.
     * @param method The method to invoke on this class.
     * @param parameter The String parameter passed to this method.
     * @param future If true then only jobs that will run are included (future).
     * @return A list of jobs that match the criterea.
     * @throws BuildingServerException
     */
    public Enumeration findJobs( String session, String method, String parameter, boolean future)
    	throws BuildingServerException
    {
    	StringBuffer where = new StringBuffer();
    	where.append(" session_name = ? AND method_name = ? AND parameter = ?");
    	if(future)
    	{
    		where.append("  AND state = ?");
    	}

    	try
    	{
    	    	PreparedStatement stmt = BuildingServer.getInstance().getContext().getConnection().prepareStatement
		(where.toString());
    	    	stmt.setString(1, session);
    	    	stmt.setString(2, method);
    	    	stmt.setString(3, parameter);
    	    	if (future)
    	    	{
    	    		stmt.setInt(4, Job.STATE_OVERDUE);
    	    	}
    	    	return Job.findJobs(stmt.toString());
		}
		catch (SQLException e)
		{
			// Shouldn't ever happen...
		}
		catch (ObjectPoolException e)
		{
			// Shouldn't happen...
		}
		return null;
    }

    private void setJobState( Job j, int s )
        {
        try
            {
            j.setState( s );
            j.save();
            }
        catch ( Exception ex )
            {
	   log.error( ex.getMessage(), ex );
            }
        }
        
    public void run()
        {
        log.debug( "JobScheduler starting." );
        try
            {
            BuildingContext context=null;
            User sysadmin;
    		PrimaryKey sysadmin_user_id;
            
            synchronized ( this )
                {
		        try
			        {
                	context = BuildingContext.startContext();
                	context.setPoolOwner( "job_scheduler" );
        	        PassPhrase pass = PassPhrase.findPassPhraseByUserName( "sysadmin" );
        	        if ( pass==null )
        		        {
				        error = "Unknown sysadmin.";
	        	        stopped=true;
        		        return;
        		        }
        	        sysadmin = pass.getUser();
        	        log.debug( "User = " + sysadmin );
        	        log.debug( sysadmin.getUserId().toString() );
        	        sysadmin_user_id = sysadmin.getUserId();
        	        }
		        catch ( Exception ex )
		        {
		            error = "Problem starting scheduler: " + ex.getMessage();
		            log.fatal( error, ex );
		            stopped=true;
		            return;
		        }
        	    finally
        	    	{
                	if ( context!=null )
   	            		BuildingContext.endContext();
        	    	}

                started=true;
                this.notify();
                }
            
	        log.info( "JobScheduler started." );
            
            int i;
            long now, exec;
            Enumeration enumeration;
            Job j;
	    JobResult job_result;
	    BigString message;
            Class c;
            Method m;
            JobSession session;
            Vector job_list=new Vector();
            User user;
            Class[] parameter_def = new Class[1];
            parameter_def[0] = String.class;
            Object[] parameter_list = new Object[1];
            
            while ( run )
            {
                // Sleep first so we never get into a race condition
                try 
                {
                    Thread.sleep( pause );  // pause in milliseconds
                }
                catch ( InterruptedException iex ){}
                
                try
                    {
                    log.debug( "JobScheduler looking for outstanding jobs." );

                	// start a context for sysadmin to fetch list of outstanding jobs
                	BuildingContext.startContext();
                	context = BuildingContext.getContext();
        			if (context == null)
        			{
        				log.warn("Unable to get bodington context, this is probably because it has shut down");
        				break;				
        			}
                	context.setPoolOwner( "job_scheduler" );
        	    	context.setUser( sysadmin );
	            	//context.setAuthenticationMethod( "internal" );
        			
                    enumeration = Job.findJobs( "state = " + Job.STATE_OVERDUE, "execution_time" );
                    
                	job_list.removeAllElements();
                	while ( enumeration.hasMoreElements() )
                    	{
                    	// stop adding jobs when the first one that is for execution later
                    	// is found
                    	j = (Job)enumeration.nextElement();
                    	if ( j.getExecutionTime().getTime() > System.currentTimeMillis() )
                        	break;
                    	job_list.addElement( j );
                    	}
	                    
                	// end the sysadmin context now the jobs are loaded
                	BuildingContext.endContext();
                    }
                catch ( BuildingServerException bsex )
                {
                    log.warn( "Error finding jobs to run: " + bsex.getMessage(), bsex );
                    continue;
                }
                    
                log.debug( "JobScheduler finished looking for outstanding jobs." );
                
                    
                for ( i=0; i<job_list.size(); i++ )
                	{
                    j = (Job)job_list.elementAt( i );
                    
                    
                    message = null;
                    job_result = null;
                    log.debug( "Executing " + j.getSessionName() + "." + j.getMethodName() + "()" );
                    try
                        {
                        context = null;

                        // now we need a context for the owner of the job
			BuildingContext.startContext();
			context = BuildingContext.getContext();
			if (context == null)
			{
				log.warn("Unable to get bodington context, this is probably because it has shut down");
				break;				
			}
			context.setPoolOwner( "job_scheduler" );
			user = User.findUser( j.getUserId() );
			if ( user == null )
				throw new NullPointerException( "Can't find owner of job." );
			context.setUser( user );
			//context.setAuthenticationMethod( "internal" );

			message = new BigString();
			message.setString( "Job Starting." );
			message.save();
			
			job_result = new JobResult();
			job_result.setJobId( j.getJobId() );
			job_result.setResultCode( JobResult.RESULT_INCOMPLETE );
			job_result.setBigStringId( message.getBigStringId() );
			job_result.setExecutionTime( new java.sql.Timestamp( System.currentTimeMillis() ) );
			job_result.save();
			
			context.setJobResult( job_result );
			
                        setJobState( j, Job.STATE_EXECUTING );
                        
                        c = Class.forName( j.getSessionName() );
                        if ( c==null )
                            {
                            log.error( "Session class not found." );
			    message.setString( "Session class not found." );
			    message.save();
			    job_result.setResultCode( JobResult.RESULT_ERROR );
			    job_result.save();
                            setJobState( j, Job.STATE_FAILED );
                            continue;
                            }
                            
                        if ( !org.bodington.server.JobSession.class.isAssignableFrom( c ) )
                            {
                            log.error( "Session class isn't a type of JobSession." );
			    message.setString( "Session class isn't a type of JobSession." );
			    message.save();
			    job_result.setResultCode( JobResult.RESULT_ERROR );
			    job_result.save();
                            setJobState( j, Job.STATE_FAILED );
                            continue;
                            }
                            
                        m = c.getMethod( j.getMethodName(), parameter_def );
                            
                        if ( m==null )
                            {
                            log.error( "Method not found in session class." );
			    message.setString( "Method not found in session class." );
			    message.save();
			    job_result.setResultCode( JobResult.RESULT_ERROR );
			    job_result.save();
                            setJobState( j, Job.STATE_FAILED );
                            continue;
                            }
                            
                        session = (JobSession)c.newInstance();
                        
                        
                        
                        // call the job now the context is set up for job owner
			parameter_list[0] = j.getParameter();
                        m.invoke( session, parameter_list );
                        
			job_result.setResultCode( JobResult.RESULT_OK );
			job_result.save();

			j.setState( Job.STATE_COMPLETED );
			// repeat job if necessary
			j.setNextExecutionTime();
			j.save();
			}
		    catch ( InvocationTargetException itex )
                	{
                	Throwable targetex = itex.getTargetException();
			log.error( "Error running job: " + targetex.getMessage(), targetex );
			try
			    {
			    if ( message!=null )
				{
				message.setString( message.getString() + "\nException executing job." + targetex );
				message.save();
				}
			    if ( job_result!=null )
				{
				job_result.setResultCode( JobResult.RESULT_ERROR );
				job_result.save();
				}
			    }
			catch ( Exception exin )
			{
			    log.error( "Error recording exception in job: " + exin.getMessage(), exin );
			}
			setJobState( j, Job.STATE_FAILED );
                        continue;
                	}
                    catch ( Exception ex )
                        {
		log.error( "Exeption running job: " + ex.getMessage(), ex );
			try
			    {
			    if ( message!=null )
				{
				message.setString( message.getString() + "\nException executing job." + ex );
				message.save();
				}
			    if ( job_result!=null )
				{
				job_result.setResultCode( JobResult.RESULT_ERROR );
				job_result.save();
				}
			    }
			catch ( Exception exin )
			    {
			    log.error("Error recording exception in job: " + exin.getMessage(), exin );
			    }
                        setJobState( j, Job.STATE_FAILED );
                        continue;
                        }
                    finally
                    	{
			// end the context no matter how things turned out
			if ( context!=null )
			    BuildingContext.endContext();
                    	}
                    
                        
                    }
                    

                    
                }
            }
        finally
            {
            stopped=true;
            the_instance = null;
            }
        }
    
    /**
     * Shutdown the JobScheduler cleanly.
     */
    public void shutdown()
    {
        log.info("Shutdown");
        run = false;
        interrupt();
    }
    }


    
   
   