#!/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',
        version => '0.0.1',
    }
);
my $s = {}; my $m = {}; my $id = shift;

# start calling
eval { $rpc->rpc_ping; };
die "Server is down! $EVAL_ERROR" if $EVAL_ERROR;
my $ok = $rpc->rpc_login;
if ($ok) {
    $s = list('student');
    create_student($id) if not exists $s->{"\t$id"};
    $s = list('student');
    $m = list('tutor');
    add_to_tutor($id) if not exists $m->{"\t$id"};
    $m = list('tutor');
    remove_from_tutor($id) if not exists $m->{"\t$id"};
    $m = list('tutor');
    destroy_student($id) if exists $s->{"\t$id"};
    $s = list('student');
    $rpc->rpc_logout;
}
else {
    print 'No access for ' . $rpc->get_login . "!\n";
    print "Wrong password?\n";
}

sub list {
    my $l = {}; my $r = shift;
    my $cmd  = 'cipux_task_list_'.$r.'_accounts';
    my $a_hr = $rpc->xmlrpc( { cmd => $cmd } );
    my $d_hr = $rpc->extract_data_for_tpl(
        { answer_hr => $a_hr, use_ltarget => 1 } );
    foreach ( @{ $d_hr->{tpl_data_ar} } ) {
        $l->{"\t".$_->{$d_hr->{ltarget}}}=1;
    }
    print ucfirst $r ."s on the system:",sort keys %{$l},"\n";
    return $l;
}

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});
}

sub add_to_tutor {
    my $s    = shift;
    my $cmd  = 'cipux_task_add_member_to_role_account';
    my $p_hr = { object => 'tutor', target => $s, };
    my $a_hr = $rpc->xmlrpc({cmd=>$cmd, param_hr=>$p_hr});
}

sub remove_from_tutor {
    my $s    = shift;
    my $cmd  = 'cipux_task_remove_member_from_role_account';
    my $p_hr = { object => 'tutor', target => $s, };
    my $a_hr = $rpc->xmlrpc({cmd=>$cmd, param_hr=>$p_hr});
}

