/* ======================================================================
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;
        fixJobs();
        this.start();
        
        synchronized( this )
            {
            for ( int i=0; !started && !stopped && i<30; i++  )
                {
                try
                    {
                    this.wait( 10000 );
                    }
                catch ( InterruptedException iex )
                    {
                    }
                }
            }
        }

    /**
     * Looks for Jobs that are currently running and sets them to overdue. 
     * This should be run before JobScheduler starts to fix any Jobs that were 
     * left in the running state when Bodington was last shutdown.
     */
    private void fixJobs()
    {
        try
        {
            Enumeration runningJobs = Job.findJobs("state = "+ Job.STATE_EXECUTING);
            int fixedJobs = 0;
            while (runningJobs.hasMoreElements())
            {
                Job job = (Job)runningJobs.nextElement();
                if (log.isDebugEnabled())
                {
                    log.debug("Resetting running job to overdue. Job ID: "
                        + job.getPrimaryKey());
                }
                setJobState(job, Job.STATE_OVERDUE);
                fixedJobs++;
            }
            if (fixedJobs > 0)
            {
                log.warn("Corrected the state to overdue of "+ fixedJobs+ " jobs.");
            }
        }
        catch (BuildingServerException bse)
        {
            log.error("Couldn't get list of jobs that might be broken.", bse);
        }
    }


    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();
	}
	
    /**
     * Schedule a new job.
     * The added Job will be run once and will be scheduled to happen from
     * now onwards.
     * @see #addJob(String, String, String, int, Calendar)
     */
    public void addJob( String session_name, String method_name, String parameter )
        throws BuildingServerException
        {
        addJob( session_name, method_name, parameter, Job.REPEAT_TYPE_ONCE );
        }

    /**
     * Schedule a new job.
     * This job will be scheduled to run from now.
     * @see #addJob(String, String, String, int, Calendar)
     */
    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());
    }
    
    /**
     * Scheduler a new job. The job is associated with the current resource.
     * @param session_name The full path of the class to run.
     * Eg: org.bodington.example.Class
     * @param method_name The method name of the method to call on this class. The 
     * method should accept a String and be an instance method. 
     * @param parameter The value of the string to pass to the method. It can't be
     * NULL but can be an empty string.
     * @param repeat_type
     * @param from The date/time to start running this Job from.
     * @throws BuildingServerException
     */
    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();
        }
    
    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." );
        BuildingContext context=null;
        try
            {
            User sysadmin;
            
            synchronized ( this )
                {
		        try
			        {
                	context = BuildingContext.startContext();
                	context.setPoolOwner( "job_scheduler" );
        	        PassPhrase pass = PassPhrase.findPassPhraseByUserName( "sysadmin" );
        	        if ( pass==null )
        		        {
				        error = "Unknown sysadmin.";
                        log.fatal("Couldn't find sysadmin user");
	        	        stopped=true;
        		        return;
        		        }
        	        sysadmin = pass.getUser();
        	        log.debug( "User = " + sysadmin );
        	        log.debug( sysadmin.getUserId().toString() );
        	        }
		        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;
	        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
                sleep();

                // Look for Jobs
                job_list = findOverdueJobs(sysadmin);
                    
                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;
            synchronized (this)
            {
                notify();
            }
            }
        }

    /**
     * Sleep for a short ammount of time.
     */
    private void sleep()
    {
        try 
        {
            Thread.sleep( pause );  // pause in milliseconds
        }
        catch ( InterruptedException iex ){}
    }
    
    /**
     * Look for jobs that we should run.
     * This method looks for Jobs that are set to OVERDUE and have an execution time
     * set to earlier than now.
     * @return A vector of Jobs to run. If there is a problem then we return an empty
     * vector.
     */
    Vector findOverdueJobs(User sysadmin)
    {
        BuildingContext context = null;
        Vector oldJobs = new Vector();
        try
        {
            log.debug( "JobScheduler looking for outstanding jobs." );
            
            // start a context for sysadmin to fetch list of outstanding jobs
            context = BuildingContext.startContext(); 
            if (context == null)
            {
                log.warn("Unable to get bodington context, this is probably because it has shut down");
            }
            else
            {
                context.setPoolOwner( "job_scheduler" );
                context.setUser( sysadmin );
                //context.setAuthenticationMethod( "internal" );
                
                Enumeration allJobs;
                Job job;
                allJobs = Job.findJobs( "state = " + Job.STATE_OVERDUE, "execution_time" );
                
                while ( allJobs.hasMoreElements() )
                {
                    // stop adding jobs when the first one that is for execution later
                    // is found
                    job = (Job)allJobs.nextElement();
                    if ( job.getExecutionTime().getTime() > System.currentTimeMillis() )
                        break;
                    oldJobs.addElement( job );
                }
            }

        }
        catch ( BuildingServerException bsex )
        {
            log.warn( "Error finding jobs to run: " + bsex.getMessage(), bsex );
        }
        finally
        {
            // end the sysadmin context now the jobs are loaded
            if (context != null)
                BuildingContext.endContext();
        }
        return oldJobs;
    }
    
    /**
     * Shutdown the JobScheduler cleanly.
     */
    public void shutdown()
    {
        log.info("Shutdown");
        if (stopped == true)
        {
            log.warn("We have already been shutdown");
        } 
        else if (started == false)
        {
            log.warn("We were never started");
        }
        else
        {
            synchronized (this)
            {
                try
                {
                    run = false;
                    interrupt();
                    // We get notified at the end of the run method
                    wait();
                    // So that we can be restarted.
                    the_instance = null;
                }
                catch (InterruptedException e)
                {
                }
            }
        }
    }
    }


    
   
   