package Requester::WatchRequester;

use strict;
use TestWorker;
use Requester::Requester;

@Requester::WatchRequester::ISA = qw(Requester::Requester);

sub request {
    my( $self, $env, $domain, $variables ) = @_;

    unless( defined $self->{"WatchRequester::freq_space"} ) {
        $self->{"WatchRequester::freq_space"} = {};
    }
    my $frequency = $env->{"sched_frequency"};
    my $handle = $self->{"WatchRequester::freq_space"}->{$frequency};
    unless( $handle ) {
        $handle = $self->{"WatchRequester::freq_space"}->{$frequency} = $self->setup_sensor( $frequency );
    }
    if( $handle->{"sched_minute"} != $env->{"sched_minute"} ) {
        $handle->{"sched_minute"} = $env->{"sched_minute"};
	my $info;
	if( $handle->{"handle"} ) {
	    $info = $self->getresults( $handle->{"handle"} );
	}
	if( $info || ! $handle->{"handle"} ) {
	    my $duration = $frequency * 60;
	    if( $duration > 120 ) { $duration -= 60; }
	      else { $duration -= 30; }
	    $handle->{"handle"} = $self->start_sensor( $handle->{"handle"}, $duration );
	}
	if( $info ) {
	    $handle->{"info"} = $info;
	}
    }
    $self->{"WatchRequester::env"} = $env;
    return $self->SUPER::request( $env, $domain, $variables );
}



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

    my $freq = $self->{"WatchRequester::env"}->{"sched_frequency"};
    my $handle = $self->{"WatchRequester::freq_space"}->{$freq};
    return( $handle->{"info"} ) if( $handle && $handle->{"info"} );
    return undef;
}


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

    while( my( $freq, $handle ) = each %{$self->{"WatchRequester::freq_space"}} ) {
        $self->abort_sensor( $handle->{"handle"} ) if( $handle->{"handle"} );
    }
}

# ------------------------------------------
# virtual methods a sub class might override

# initialize sensor and return a handle (I wouldn't override this :-))
sub setup_sensor {
    my( $self, $frequency ) = @_;

    return { "sched_minute", "-1" };
}
    

# initiate one sensor run - the handle is the former $handle returned
# by former runs of start_sensor, the $duration is the suggested duration
# the sensor should run in seconds (something like frequency - a few seconds)
# start_sensor() must return a handle (or undef)
sub start_sensor {
    my( $self, $handle, $duration ) = @_;
    return undef;
}


# get results of a sensor run - the handle passed is the same one that
# was returned by the preceding start_sensor() call
sub getresults {
    my( $self, $handle ) = @_;

    return undef;
}


# stop a sensor started with start_sensor() without polling for results
# via getresults()
sub abort_sensor {
    my( $self, $handle ) = @_;

    # by default getresults() will terminate a sensor - so just call it
    # without caring for the results
    $self->getresults( $handle );
}

1;
