package Schedule;

require 5.001;

my $start_time = time;

use strict;

use CWorker;
use MicroTime;
use vars qw( $profile );

$profile = 0;


sub schedule {
    my( $objs, $time, @args ) = @_;

    my $obj;
    # XXX:  Should this check for $time<$start_time?
    my $minute = ($time!=0)?int(($time-$start_time)/60):0;
    my $old_niceness = 0;
    foreach $obj (sort { $a->niceness() <=> $b->niceness() } @$objs) {
	my $niceness = $obj->niceness();
	if( $niceness != $old_niceness ) {
	    CWorker::do_them();
	    $old_niceness = $niceness;
	}
        my $time;
	if( $profile ) {
	    $time = MicroTime::gettimeofday();
	}
	$obj->sched_run( $minute, @args );
	if( $profile ) {
	    $time = MicroTime::difftime( $time );
	    if( $time > 0.5 ) {
	        BigSister::common::log( "info", "profile: Scheduler spent ".(int($time*100)/100)."s in $obj\n" );
	    }
	}
	CWorker::one_pass();
    }
    CWorker::one_pass();
}


sub new
{
    my ($this, $frequency, $procedure) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};

    bless($self, $class);
    $self->sched_init( $frequency, $procedure );

    return($self);
}


sub sched_init {
    my ($self, $frequency, $procedure) = @_;
    
    ($frequency = 5) unless( $frequency );
    $self->{"sched_frequency"} = $frequency;
    ($self->{"sched_procedure"} = $procedure) if( $procedure );
}


sub sched_run {
    my( $self, $minute, @args ) = @_;

    $self->{"sched_minute"} = $minute;
    unless( $self->{"sched_frequency"} ) {
	$self->sched_init();
    }
    return if( $self->{"sched_frequency"} eq "none" );
    return if( $minute % $self->{"sched_frequency"} );
    return( $self->run( @args ) );
}


sub run {
    my( $self, @args ) = @_;

    if( $self->{"sched_procedure"} ) {
	$self->{"sched_procedure"}->( @args );
    }
}



sub sched_frequency {
    my( $self, $frequency ) = @_;

    ($frequency = 5) unless( $frequency );
    $self->{"sched_frequency"} = $frequency;
}



sub sched_procedure {
    my( $self, $procedure ) = @_;

    $self->{"sched_procedure"} = $procedure;
}


sub sched_gettime {
    my( $self ) = @_;
    
    (defined $self->{"sched_minute"}) || return(-1);
    return( $self->{"sched_minute"} );
}


sub niceness {
    return 0;
}

	     
1;
