#!/usr/bin/perl -w

package TVData;


use strict;
use IPC::Open3;

sub new {
    my $class= shift;

    my ($reader, $writer, $pid)= startTvProcess();

    return bless {
        reader=>$reader,
        writer=>$writer,
        pid=>$pid,
        tvreadbufsize=>256,
    }, $class;
}

sub DESTROY {
    my $self= shift;
    print "start terminating tv process\n";
    $self->{writer}->syswrite("q", 1);
    $self->{reader}->close();
    waitpid($self->{pid},0);
    print "cleaned up tv process $self->{pid}\n";
}

sub read {
    my $self= shift;

    my $readdata="";
    my $bytesread= $self->{reader}->sysread($readdata, $self->{tvreadbufsize}) || 0;
    return $readdata;
}

sub startTvProcess {
    my $reader= IO::Handle->new();
    my $writer= IO::Handle->new();
    my $error= IO::Handle->new();
# todo: must make aatv believe it runs in a 80x25 window
#    my $pid= open3($writer, $reader, $error, "aatv -fps 5 -kbddriver stdin -driver slang") or die "can't start aatv : $!\n";
    my $pid= open3($writer, $reader, $error, "nc itsme.dyndns.org 24|compress -d") or die "can't start aatv : $!\n";
    
    $reader->blocking(0);
    $writer->blocking(0);
    $error->blocking(0);

    return ($reader, $writer, $pid);
}


1;
