#!/usr/bin/perl -w

package tvclient;

use strict;

use Socket; # sockaddr_in
use Compress::Compress;

sub new {
    my $class= shift;

    my ($client, $packedaddress)= @_;  # from accept

    if (!defined $client) { return undef; }

    my ($port, $inetaddr)= sockaddr_in($packedaddress);
    my $numericaddress= inet_ntoa($inetaddr);

    return bless {
        client=>$client,
        address=>$numericaddress,
        port=>$port,
        compressor=>Compress::Compress->new(),
        description=>"$numericaddress:$port",
        data=>"",
        stats_alltvdata=>0,
        stats_compressed=>0,
        stats_uncompressed=>0
    }, $class;
}

sub DESTROY {
    my $self= shift;
    return if (!defined $self->{client});

    print "start cleaning up tvclient $self->{description}\n";
    
    $self->{client}->close();
    delete $self->{compressor};
    print "cleaned up tvclient $self->{description}\n";
}

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

    $self->{compressor}->write($data);
    my $compresseddata= $self->{compressor}->read();
    $self->{stats_uncompressed} += length($data);
    $self->{stats_compressed} += length($compresseddata);
    #todo: first test if socket still connected.
    my $rv= $self->{client}->send($compresseddata, 0);
}
1;
