package APKPM::Davolink;

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

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

use Redis;

use lib '/opt/managment_tools/lib';
use H1::Davolink;

sub prefix { 'Davolink_' }

sub info : Job : Decode(d_array) : Encode(e_json) {
	my ( $self, $job, $workload ) = @_;
	warn "# workload = ", dump $workload;
	my $cpeip = shift @$workload;
	my $username = shift @$workload;

	unshift @$workload, 'adsl'; # add default

	return { error => "invalid workload", expected => 'cpe.ip username (uptime|adsl|wan|routes)', workload => $workload } unless $cpeip && $username;

	my $cpeconnect=H1::Davolink->new($cpeip,$self->config('iadusername'),$self->config('iadpasswd'));
	$cpeconnect->connect() || return { error => "can't connect to $cpeip" };
	my $ret = { ip => $cpeip, username => $username };
	foreach my $param ( @$workload ) {
		if ( $param =~ m/uptime/i ) {
			$ret->{UPTIME} = $cpeconnect->custom("cat /proc/uptime");
		} elsif ( $param =~ m/adsl/i ) {
			$ret->{ADSL} = { $cpeconnect->adsl_info };
			$self->do_background_json( 'Store_insert', {
				_table => 'adsl',
				ip => $cpeip,
				username => $username,
				timestamp => $self->datetime_now,
				%{$ret->{ADSL}}
			});
			my $redis = Redis->new;
			$redis->sadd( 'poll.adsl.ok' => $cpeip );
		} elsif ( $param =~ m/wan/i ) {
			$ret->{WAN} = [ $cpeconnect->wan_info ];
		} elsif ( $param =~ m/route/i ) {
			$ret->{ROUTES} = [ $cpeconnect->route_info ];
		} else {
			die "unknown param $param";
		}
	};

	return $ret;
}

1;
