#!/usr/bin/perl -w

#  You may distribute under the terms of the GNU General Public License
#
#  (C) Paul Evans, 2008-2010 -- leonerd@leonerd.org.uk

use strict;

# Until we have a real CPAN dist...
use lib ".";

use Tangence::Connection;

use IO::Async::Loop 0.16;

use Data::Dump;

my $loop = IO::Async::Loop->new();

my $URL = shift @ARGV or die "Need URL as argv[1]\n";

my $objid = 1;
if( $ARGV[0] eq "-o" ) {
   shift @ARGV; # eat -o
   $objid = shift @ARGV;
}

my $method = shift @ARGV;

my @args = @ARGV;

my $conn = Tangence::Connection->new(
   on_closed => sub {
      print STDERR "Connection closed\n";
      exit(0);
   },
   on_error => sub {
      my ( $message ) = @_;
      print STDERR "Error: $message\n";
      $loop->loop_stop;
   },
);

$loop->add( $conn );

$conn->connect( 
   $URL,
   on_connected => sub {},
);

my $registry;
$loop->loop_once until defined( $registry = $conn->get_registry );

$registry->call_method(
   method => "get_by_id",
   args   => [ $objid ],

   on_result => sub {
      my ( $obj ) = @_;

      $obj->call_method(
         method => $method,
         args   => \@args,
      
         on_result => sub {
            my ( $result ) = @_;
            print STDERR "Result of call was:" . Data::Dump::dump($result) . "\n";
            $loop->loop_stop;
         },
      );
   },
);

$loop->loop_forever;
