#!/usr/bin/perl

package Cog; # persistant Gearman Worker - see the pun?

use Moose;
use JSON::XS qw();
extends 'Gearman::Driver::Worker::Base';

use lib 'lib';
with 'APKPM::Gearman';
with 'APKPM::Gearman::Client';

sub prefix { '' }

package main;

use Gearman::Driver;
use Data::Dump qw(dump);

use lib 'lib';
use H1::ZTEDSLAM;

my $driver = Gearman::Driver->new(
	server   => 'localhost:4730',
	interval => 60,
	loglevel   => 'DEBUG',
	logfile    => 'log/persistant.log',
) || die $!;

my $w1 = 'Cog';
my $worker = $w1->new();

warn "CRM_search";
my $crm = $worker->do( 'CRM_search' => "TIP_UREDJAJA:ZTEDSLAM" );

my $poll;

foreach my $user ( @$crm ) {
	$poll->{ $user->{IP_UREDAJA} }->{ $user->{SHELF_SLOT_PORT} }++;
}

warn "# poll = ", dump($poll);

foreach my $ip ( keys %$poll ) {

	my $method = "ZTEDSLAM_$ip";

	$driver->add_job({
		max_processes => 1, # FIXME increase?
		min_processes => 1,
		name		=> $method,
		worker		=> $worker,
		methods	   => [
			{
				decode => 'd_json',
				encode => 'e_json',
				name   => $method,
				body   => sub {

		my ( $self, $job, $crm ) = @_;
		my $hash;
		eval { $hash = H1::ZTEDSLAM->hash( $ip, $crm->{SHELF_SLOT_PORT} ) };

		return { error => $@ } if $@;

		$self->do_background_json( 'Store_insert', {
			_table => 'dslam_h',
			ip => $crm->{IP_MANAGEMENT}, # FIXME IP_UREDAJA ?
			username => $crm->{USERNAME},
			timestamp => $self->datetime_now,
			h => $self->to_hstore($hash),
		});

#		return $hash; # body end

				},
			},
		]
	});

	warn "$method added\n";

}

$driver->add_job({
	max_processes => 1,
	min_processes => 1,
	worker		=> $worker,
	methods	   => [ {
		name		=> 'poll_ZTEDSLAM',
		body   => sub {

		my ( $self, $job, $workload ) = @_;

		my $crm = $self->do( 'CRM_search' => "TIP_UREDJAJA:ZTEDSLAM" );

		warn "# crm $crm";

		my $taskset = $worker->gc->new_task_set;
		my $seen;

		foreach my $user ( @$crm ) {
			my $name = 'ZTEDSLAM_' . $user->{IP_UREDAJA};
			$taskset->add_task( $name, $self->e_json( $user ), {
				on_complete => sub { "# $name done ", dump($user), $/ }
			} )
			if ! $seen->{ $user->{IP_UREDAJA} }->{ $user->{SHELF_SLOT_PORT} }++;
		}
		warn "# wait";
		$taskset->wait;

		warn "# seen ", dump($seen);

		return; # body end
		}
	} ],
});

$driver->run;

