#!/usr/bin/perl -w

package Compress::Compress;

use strict;

use IO::Handle;
use IPC::Open3;
#@EXPORT = qw(new write read);

sub new {
    my $class= shift;

    my ($reader, $writer, $pid)= startCompressProcess();
    print "created compressor $pid\n";
    return bless {
        pid=>$pid,
        reader=>$reader,
        writer=>$writer,
        data=>""
    }, $class;
}

sub DESTROY {
    my $self= shift;

    print "start cleaning up compressor $self->{pid}\n";

    $self->flush();

    print "cleaned up compressor $self->{pid}\n";
}

sub read {
    my $self= shift;

    $self->readProcess();

    my $readdata= $self->{data};
    $self->{data}="";
    return $readdata;
}

sub write {
    my $self= shift;
    my $data= shift;

    my $r= $self->{writer}->syswrite($data, length($data));

    $self->readProcess();
}

sub flush {
    my $self= shift;
    return if (!defined $self->{writer});
    #todo: check if process still exists.
    $self->{writer}->close();
    waitpid($self->{pid}, 0);
    $self->readProcess();
}

sub readProcess {
    my $self= shift;
    return if (!$self->{reader});
    my $readdata;
    my $readbytecount=0;
    while (my $nr=$self->{reader}->sysread($readdata, 256)) {
        $self->{data} .= $readdata;
        $readbytecount += $nr;
    }
}
sub startCompressProcess {
    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, "compress") or die "can't start compress : $!\n";
    
    $reader->blocking(0);
    $writer->blocking(0);
    $error->blocking(0);

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

1;
