package APKPM::EasyGateway;

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 SOAP::Lite;

sub prefix { 'EasyGateway_' }

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

	my $ip = $workload;

	return { error => "invalid workload", expected => 'cpe.ip', workload => $workload } unless $ip;

	my $ret;

	my $soap = SOAP::Lite
		->service('http://10.99.0.74:9090/cpews/services/Cpe112DiagnosisSoapImpl?WSDL');

	my $out = $soap->getWanDslStatus( "IP=$ip" );

	$ret->{$_} = $out->{$_} foreach keys %$out;

	my $out = $soap->getCpeBasicInfo( "IP=$ip" ); # mac, username, uptime

	foreach ( keys %$out ) {
		next unless defined $out->{$_}; # skip undef values
		$ret->{$_} = $out->{$_};
	}

	$self->do_background_json( 'Store_insert', {
		_table => 'easygateway',
		ip => $ip,
		username => $ret->{customerName},
		timestamp => $self->datetime_now,
		h => $self->to_hstore( $ret ),
	});

	my $redis = Redis->new;
	$redis->sadd( 'CPE.EasyGateway.ok' => $ip );

	return $ret;
}

1;
