package APKPM::Poll;

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

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

sub prefix { 'poll_' }

sub by_prefix : Job : MinProcesses(1) : MaxProcesses(1) : Encode(e_json) {
	my ( $self, $job, $workload ) = @_;

	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]} }
		});
	}

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

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

sub ip_username : Job : MinProcesses(1) : MaxProcesses(25) : 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);

	if ( exists $ping->{error} ) {
		return $ping;
	}

	$ping->{username} = $username;
	$self->do_background_json( 'Store_ping', $ping );

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

	return $ping;
}

1;
