#!/usr/bin/perl -w
###################################################
use Getopt::Long;
use Data::Dumper;
use SOAP::Lite
#    trace => 'debug',
    soapversion => '1.2';
$HOST   = "http://localhost:8080/";
# Need to figure out how to set the namespace
$NS     = "urn:WSZakim";

# Parse options
my $help = 0;
my $loc = $HOST;

sub usage() {
    my $a = shift;
    my $error = shift;
    if ($error) {
	print STDERR "$error\n\n";
    }
    print STDERR "Usage: $0 [options] <functions>\n";
    print STDERR "\nFunctions:\n";
    print STDERR "  list			List active teleconferences\n";
    print STDERR "  call <code> <caller>	Call \$caller and join conference with code \$code\n";
    print STDERR "  attendees <conf>	Get the list of attendees on \$conf; \$conf is a substring\n";
    print STDERR "  create <number>	Create an ad-hoc teleconference for \$number participants";
    print STDERR "\nOptions:\n";
    print STDERR "  --help		this help message\n";
    print STDERR "  --location <URL>	location of WS-Zakim service (d: $HOST)\n";
    exit($a);
}

GetOptions('help' => \$help,
    'location=s' => \$loc);

if ($help) {
    &usage(0);
}

if ($#ARGV < 0) {
    &usage(1, 'You need to specify a function');
}

my $function = shift;

sub getargs() {
    my $number = shift;
    if ($#ARGV < ($number - 1)) {
	&usage(1, 'Not enough arguments');
    }
    splice(@ARGV, $number);
    return @ARGV;
}

sub checkforfault() {
    my ($som) = @_;
    return if (! $som->fault);
    print "Something went wrong. SOAP fault received.\n\n";
    print "Fault code: " . $som->faultcode . "\n";
    print "Reason: " . $som->faultstring . "\n";
    exit(10);
}

my $soap = SOAP::Lite
    ->readable(1)
    ->uri($NS)
    ->proxy($loc);

my $result;

if ($function eq 'call') {
    my ($conf, $caller) = &getargs(2);
    my $som = $soap->callMe(
			    SOAP::Data->name("conference" => "$conf"),
			    SOAP::Data->name("caller" => "$caller")
			    );
    &checkforfault($som);
    $result = $som->result;
} elsif ($function eq 'attendees') {
    my ($conf) = &getargs(1);
    my $som = $soap->attendees(
			       SOAP::Data->name("conference" => "$conf"),
			       );
    &checkforfault($som);
    $result = join(' ', @{$som->result});
} elsif ($function eq 'list') {
    $som = $soap->listConferences();
    &checkforfault($som);
    $result = join(' ', @{$som->result});
} elsif ($function eq 'create') {
    my ($number) =  &getargs(1); # read from the command line
    $som = $soap->createConference(
				   SOAP::Data->name("participants" => "$number"),
				   );
    &checkforfault($som);
    $result = Dumper($som->result);
} else {
    &usage(1, "Unknown function $function");
}

print "The response from the service was:\n".$result."\n";
