
use Tk;
use strict;

use Fcntl;

use IO::File;

use Term::ReadKey;
# ReadMode 3;


#my $fh = (*STDIN);
#$fh->autoflush(1);
#fcntl(*STDIN, F_SETFL,
#      fcntl(*STDIN, F_GETFL, 0) | O_NONBLOCK);
# local($/) = '';

my $mw = new MainWindow;
$mw->configure(-title => 'TmmRemote/GUI');
$mw->Button(
	    -text => 'Exit',
	    -command => sub { Tk::exit; },
	   )->pack;

my $text = $mw->Text(
		     -width => 80,
		     -height => 30,
		     -font => '-misc-gothic-medium-r-normal--14',
		    )
  ->pack(-side => 'left', -fill => 'y');

my $scrollbar = $mw->Scrollbar(
			       -command => ['yview', $text],
			      )
  ->pack(-side => 'right', -fill => 'y');

$text->configure(-yscrollcommand => ['set', $scrollbar]);


$mw->fileevent(\*STDIN, 'readable' => \&dataevent);

my $after = $mw->repeat(500,
			sub {
#			  $text->insert('end', "ABCEF\n");
#			  print "timer...\n";
			});

MainLoop;

ReadMode 0;


my $windowsdata = {};
my $windows = {};
sub dataevent {
#  my $str;
#  sysread(*STDIN, $str, 1);

  if(eof(STDIN))
    {
      print STDERR "close filehandle...\n";
      $mw->fileevent(\*STDIN, 'readable' => '');
      return;
    }
  
  my $line = <STDIN>;
  print STDERR $line;

  if($line =~ s/^\(([^\)]+)\) ?//)
    {
      my $server = $1;
      if(! exists($windows->{$server}))
	{
	  my $mw = new MainWindow;
	  $windowsdata->{$server}{mw} = $mw;

	  $mw->configure(-title => $server);
	  
	  my $text = $mw->Text(
			       -width => 80,
			       -height => 30,
			       -font => '-misc-gothic-medium-r-normal--14',
			      )
	    ->pack(-side => 'left', -fill => 'y');
	  $windowsdata->{$server}{text} = $text;

	  my $scrollbar = $mw->Scrollbar(
					 -command => ['yview', $text],
					)
	    ->pack(-side => 'right', -fill => 'y');
	  $windowsdata->{$server}{scrollbar} = $scrollbar;

	  $text->configure(-yscrollcommand => ['set', $scrollbar]);

	  $windows->{$server} = $text;
	}

      $windows->{$server}->insert('end', $line);
    }
  else
    {
      $text->insert('end', $line);
    }
  
}


