#!/usr/bin/perl -w

use strict;
use IO::Socket::UNIX;
use NOCpulse::Notif::EscalatorOperation;

use Storable qw (freeze thaw);

$|=1;

print "Creating client\n";

#my $host="localhost";
#my $port=9000;
#my $client = IO::Socket::UNIX->new(PeerHost  => $host,
#                                   PeerPort  => $port,
#                                   Proto     => 'tcp',
#                                   Timeout   => 30 )
#    or die $@;

for (my $i=1; $i<=50; $i++) {
my $client = IO::Socket::UNIX->new(Peer      => "/tmp/mysock",
                                   Type      => SOCK_STREAM,
                                   Timeout   => 10 )
    or die $@;

my $HEADER_BYTES=8;


if ($client->connected) {
    print "Client is connected\n";
} else {
    print "ERROR, Client is NOT connected\n";
}

print "Writing to client\n";

# … do something with the client
my $op= NOCpulse::Notif::EscalatorOperation->new(operation => 'blah');
$op->parameters_push(1 .. 5000);

my $item = freeze($op);
my $length = length($item);
my $string = sprintf("%${HEADER_BYTES}.${HEADER_BYTES}i%s",$length, $item);
print $client $string;

print "Getting answer from the client\n";
#$answer = <$client>;

# Check how many bytes to read
my $bytes;
read ($client, $bytes, $HEADER_BYTES); 
$length = $length + 0;

# Read those bytes
my $answer;
read ($client, $answer, $bytes); 

my $obj=thaw($answer);
    
if ($obj) {
    $op->results($obj->results);
    print "client: the answer is $answer\n";
} else {
    print "no answer from server\n"
}

print "Closing the client\n";
# and terminate the connection when we're done
close ($client);
sleep(1);
}
