package APKPM::CRM;

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

with 'APKPM::Config';

require RPC::XML;
require RPC::XML::Client;

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

sub prefix { 'CRM_' }

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 username : Job : MinProcesses(1) : MaxProcesses(5) : Encode {
	my ( $self, $job, $workload ) = @_;
	warn "# username ",dump($workload);
	my $cli = RPC::XML::Client->new($self->config('crmxml'));
	my $resp = $cli->send_request('search',RPC::XML::array->new(
		USERNAME => '%' . $workload . '%'
	));
	return ref $resp ? $resp->value->[0] : { error => $resp };
}

sub encode {
	my ( $self, $result ) = @_;
	my $json = JSON::XS::encode_json($result);
	warn "## ", dump $json;
	return $json;
}

1;
