#!/usr/bin/perl -w
#
# muxdemo - Simple demonstration of IO::Muxer
#
# Copyright (C) 2008 Oskar Liljeblad
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use strict;
use IO::Muxer;
use IO::Socket;

my $mux = IO::Muxer->new(__PACKAGE__);
my $socket = IO::Socket::INET->new(Listen=>5, ReuseAddr=>1, Proto=>'tcp', LocalPort => 9000);
$mux->listen($socket);
print "program started, listening on 9000/tcp\n";
$mux->loop();
print "program terminated\n";

sub mux_error($$$$) {
  my ($this, $mux, $fh, $syscall) = @_;
  if (defined $fh) {
    print "mux_error on $fh during $syscall\n";
    $mux->close($fh);
  } else {
    print "mux_error during $syscall\n";
  }
}

sub mux_timeout($$$) {
  my ($this, $mux, $fh) = @_;
  print "mux_timeout on $fh\n";
  $mux->write($fh, "TIMEOUT\n");
}

sub mux_connection($$$$) {
  my ($this, $mux, $fh, $newfh) = @_;
  print "mux_connection on $fh - $newfh\n";
  $mux->add($newfh);
}

sub mux_eof($$$$) {
  my ($this, $mux, $fh, $bufref) = @_;
  print "mux_eof on $fh\n";
  $mux->close($fh);
}

sub mux_input($$$$) {
  my ($this, $mux, $fh, $bufref) = @_;
  print "mux_input on $fh\n";
  while (${$bufref} =~ s/(.*?)\r?\n//m) {
    my $cmd = $1;
    $mux->write($fh, "OK $cmd\n");
    if ($cmd eq 'exit') {
      $mux->close_when_flushed($fh);
    } elsif ($cmd =~ /^timeout (\d+)$/) {
      $mux->set_timeout($fh, $1);
    }
  }
}

sub mux_connected($$$) {
  my ($this, $mux, $fh) = @_;
  print "mux_connected on $fh\n";
  $mux->write($fh, "WELCOME\n");
}
