#!/usr/bin/perl -w
use strict;
use CipUX::RPC::Client;
use English qw( -no_match_vars);

# prep
my $rpc = CipUX::RPC::Client->new(
    {
        url     => 'http://localhost:8001/RPC2',
        client  => 'cipux_rpc_task_create_destroy_test_two_times',
        version => '0.0.1',
    }
);
my $s   = {};
my $id1 = shift;
my $id2 = shift;
chomp $id1;
chomp $id2;

# start calling
eval { $rpc->rpc_ping; };
die "Server is down! $EVAL_ERROR" if $EVAL_ERROR;
my $ok = $rpc->rpc_login;
if ($ok) {
    list_students();
    print "create [$id1]\n";
    create_student($id1) if not exists $s->{"\t$id1"};
    list_students();
    print "create [$id2]\n";
    create_student($id2) if not exists $s->{"\t$id2"};
    list_students();

    destroy_student($id1) if exists $s->{"\t$id1"};
    list_students();
    destroy_student($id2) if exists $s->{"\t$id2"};
    list_students();
    $rpc->rpc_logout;
}
else {
    print 'No access for ' . $rpc->get_login . "!\n";
    print "Wrong password?\n";
}

sub list_students {
    my $cmd  = 'cipux_task_list_student_accounts';
    my $a_hr = $rpc->xmlrpc( { cmd => $cmd } );
    my $d_hr = $rpc->extract_data_for_tpl(
        { answer_hr => $a_hr, use_ltarget => 1 } );
    $s = {};
    foreach ( @{ $d_hr->{tpl_data_ar} } ) {
        $s->{ "\t" . $_->{ $d_hr->{ltarget} } } = 1;
    }
    print "Students on the system:", sort keys %{$s}, "\n";
}

sub create_student {
    my $s    = shift;
    my $cmd  = 'cipux_task_create_student_account';
    my $p_hr = { object => $s, };
    my $a_hr = $rpc->xmlrpc( { cmd => $cmd, param_hr => $p_hr } );
}

sub destroy_student {
    my $s    = shift;
    my $cmd  = 'cipux_task_destroy_student_account';
    my $p_hr = { object => $s, };
    my $a_hr = $rpc->xmlrpc( { cmd => $cmd, param_hr => $p_hr } );
}
