package Statusmon::TrackLast;

use Statusmon::Statusmon;

@Statusmon::TrackLast::ISA = qw(Statusmon::Statusmon);


sub new
{

    my ($this) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};

    bless($self, $class);

    $self->{"statedir"} = "$BigSister::common::fs{'web'}/logs";
    $self->{"lastupdate"} = {};
    $self->{"starttime"} = time;
    $self->{"expiries"} = {};
    $self->add_feature_provider( "timetracker" );
    $self->sched_frequency( 8 );
    return($self);
}


sub start {
    my( $self ) = @_;
    $self->register( "config" );
    $self->register( "status" );
    my $config = $self->get_feature_provider( "displayconfig" );
    if( $config ) { $self->read_config( $config->get_current_config() ) };
}
    

sub read_config {
    my( $self, $newconfig, $oldconfig ) = @_;

    $self->{"config"} = $newconfig;
}



sub event {
    my( $self, $cmd ) = @_;

    print STDERR "Statusmon::TrackLast got ".($cmd->{"cmd"})." event\n" if( $BigSister::common::dl>6 );

    if( $cmd->{"cmd"} eq "status" ) {
	$item = ($cmd->{"host"}).".".($cmd->{"check"});
	$self->{"lastupdate"}->{$item} = time;
	$self->{"expiries"}->{$item} = time + 60*$cmd->{"expires"};
    }
    elsif( $cmd->{"cmd"} eq "displayconfig" ) {
	$self->read_config( $cmd->{"config"}, $cmd->{"previous_config"} );
    }
}



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

    my @hosts = $self->get_hosts();
    my $now = time;
    for( my $h=0; $h<=$#hosts; $h++ ) {
	my $host = $hosts[$h];
	my @checks = $self->get_checks( $host );
	my $now = time;
	for( my $i=0; $i<=$#checks; $i++ ) {
	    my $check = $checks[$i];
	    #my $last = $self->get_lastupdate( $host, $check );
	    my $expires = $self->get_expires( $host, $check );
	    if( $now > $expires ) {
		$self->loopback( (time)." 127.0.0.1: status $host.$check purple (".(time).") ".(
		    scalar localtime )." no status report" );
	    }
	}
    }
}


# =============== feature provider stuff ==============================

sub get_lastupdate {
    my( $self, $host, $check ) = @_;

    ($host .= ".".$check) if( $check );
    my $time = $self->{"lastupdate"}->{$host};
    ($time = $self->{"starttime"}) unless( $time );
    return $time;
}


sub get_expires {
    my( $self, $host, $check ) = @_;

    ($host .= ".".$check) if( $check );
    my $time = $self->{"expiries"}->{$host};
    return( $time ) if( $time );
    return $self->get_lastupdate( $host ) + 900;
}

1;
