package APKPM::Poll;

use base qw(Gearman::Driver::Worker);
use Moose;
use Time::HiRes qw(time);
use Data::Dump qw(dump);
use Redis;

with 'APKPM::Gearman::Client';
with 'APKPM::Gearman';

sub prefix { '' }

sub poll_prefix : Job : Encode(e_json) {
	my ( $self, $job, $workload ) = @_;

	my $redis = Redis->new;
	$redis->del( $_ ) foreach $redis->keys('poll.*');

	my $start = $self->datetime_now;

	$redis->set( 'poll.start' => $start );

	my $entries = $self->do( 'LDAP_search' => "(&(cn=$workload*)(dhcpStatements=*))" );

	my $ip_username;
	foreach my $entry ( @$entries ) {
		$ip_username->{ $entry->{cn} } = $1 if $entry->{dhcpStatements} =~ m/fixed-address\s+(\S+)/;
	}

	my $taskset = $self->gc->new_task_set;
	my $results;
	while (my ($username,$ip) = each %$ip_username) {
		$taskset->add_task('poll_ip_username', "$ip $username", {
			on_complete => sub { push @$results, ${$_[0]} }
		});
		$redis->sadd('poll.queued' => $ip);
	}

	warn "# wait";
	$taskset->wait;

	my $finish = $self->datetime_now;
	$redis->set( 'poll.finish' => $finish );

	my $poll;
	foreach my $k ( $redis->keys('poll.*') ) {
		my $n = $k;
		$n =~ s/^poll\.//;
		$n =~ s/\./_/g;
		$poll->{$n} = eval { $redis->scard($k) } || $redis->get($k);
	}

	warn dump $poll;
	$self->do_background_json('Store_insert', { _table => 'poll', %$poll });

	return { ldap => $ip_username, results => $results, poll => $poll };
}

sub poll_ip_username : Job : Decode(d_array) : Encode(e_json) {
	my ( $self, $job, $workload ) = @_;

	my ( $ip, $username ) = @$workload;

	return { error => "invalid workload", expected => "ip username" } unless $ip && $username;
	my $ping = $self->do('ping', $ip);

	my $redis = Redis->new;

	if ( exists $ping->{error} ) {
warn "XXX error: $ip";
		$redis->sadd( 'poll.ping.error' => $ip );
		return $ping;
	} else {
		$redis->sadd( 'poll.ping.ok' => $ip );
	}

	$ping->{username} = $username;
	$ping->{timestamp} = $self->datetime_now;
	$self->do_background_json( 'Store_insert', {
		 _table => 'ping',
		username => $username,
		timestamp => $self->datetime_now,
		%$ping
	});

	$self->do_background( 'Davolink_info', "$ip $username adsl" );

	return $ping;
}

1;
