#!/usr/bin/perl -w

use strict;

use Test::More tests => 41;
use RFID::Alien::Reader::TCP;
use RFID::Alien::Reader::Test;
use RFID::EPC::Tag;
use IO::Socket::INET;

my $test = RFID::Alien::Reader::Test->new(
					  Debug => $ENV{ALIEN_DEBUG},
					  )
    or die "Couldn't create test object\n";
my $listen = IO::Socket::INET->new(Proto => 'TCP',
				   Listen => 5,
#				       LocalPort => 9999,
				   LocalAddr => 0,
				   )
    or die "Couldn't create listening socket: $!\n";
my $port = $listen->sockport;

# Start up a server.
our $pid;
if ($pid = fork)
{
    # Parent
}
elsif (!defined($pid))
{
    # Error
    die "Fork error: $!\n";
}
else
{
    # Suppress errors since otherwise we get error messages on
    # Windows.
    eval {
	if (my $sock = $listen->accept)
	{
	    $sock->autoflush(1);
	    $test->run($sock,$sock);
	}
    };
    exit(0);
}

our $obj;
eval {
    # Parent
    sleep(1);
    $SIG{ALRM}=sub { die "Timed out\n" };
    alarm(20); # Maximum time we'll wait.
    $obj = RFID::Alien::Reader::TCP->new(PeerAddr => 'localhost', 
					 PeerPort => $port,
					 Debug => $ENV{ALIEN_DEBUG},
					 );
    isa_ok($obj,'RFID::Alien::Reader::TCP');
    isa_ok($obj,'RFID::Alien::Reader');
    
    do 't/readertest.pl'
	or die "Couldn't do t/readertest.pl: $@/$!\n";
};

warn $@ if $@;
undef $obj; # Required to prevent hangs on Windows

kill 'TERM',$pid;

1;
