package APKPM::DSLAM;

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

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

require RPC::XML;
require RPC::XML::Client;
use Encode;

#$RPC::XML::ENCODING = "utf-8"; # FIXME really used?

sub prefix { 'DSLAM_' }

sub process_name {
	my ( $self, $orig, $job_name ) = @_;
	warn "# process_name $orig $job_name\n";
	return "$orig ($job_name)";
}

sub begin {
	my ( $self, $job, $workload ) = @_;
	warn "# begin ", dump( $workload );
}

sub search : Job : Encode(e_json_encode) {
	my ( $self, $job, $workload ) = @_;
	warn "# search ",dump($workload);

	my ($field,$value);

	if ( $workload =~ m/[:=]/ ) {
		($field,$value) = split(/[:=]/,$workload,2)
	} else {
		return { error => 'invalid workload', expected => 'OPT_82:%' };
	}

	my $cli = RPC::XML::Client->new($self->config('crmxml'));
	warn "RPC::XML $field $value";
	my $resp = $cli->send_request('ports',RPC::XML::array->new( $field => $value ));
	return ref $resp ? $resp->value->[0] : { error => $resp };
}

sub e_json_encode {
	my ($self,$data) = @_;
	my $json = $self->e_json($data);
	$json = Encode::decode('utf-8', $json);
	Encode::from_to($json,'cp1250', 'utf-8');
	return $json;
}

1;
