#!/usr/bin/perl
use warnings;
use strict;

use IO::Socket::INET;
use Data::Dump qw(dump);

my $sock = IO::Socket::INET->new(
	PeerAddr => '127.0.0.1',
	PeerPort => 4730,
	Proto    => 'tcp'
) || die $1;

print "[2J"; # Erase Screen

my $t = time();
my $max;
my $erase_screen = 1;
my $last_names = '?';

while(1) {
	my $uptime = time() - $t;
	print "[2J" if $erase_screen || $uptime % 5 == 0;
	print "[0;0H"; # Cursor Home
	print "Gearman " . localtime(time()) . "\t[34mmax update: $uptime[0m\n"; 
	printf "[4mqueued  running  wrk function[0m\n";

	print $sock "STATUS\n";

	my $names;

	while ( my $line = <$sock> ) {
		chomp $line;
#		warn "# [$line]\n";
		last if $line eq '.';
		next if $line =~ m/\t0$/; # ignore functions which don't have active workers
		my ( $name, $queued, $running, $workers ) = split(/\t/,$line,4);
		next if ! $ENV{ALL} && $queued == 0;
		$max->{$name}->{$_} ||= 0 foreach qw(queued running);
		$max->{$name}->{queued}  = $queued  if $queued > $max->{$name}->{queued};
		$max->{$name}->{running} = $running if $running > $max->{$name}->{running};
		printf "%3d [34m%-3d[0m %3d [34m%-3d[0m %3d  %s\n"
			, $queued,  $max->{$name}->{queued}
			, $running, $max->{$name}->{running}
			, $workers
			, $name
		;
		$names .= $name;
	}

=for workers
	print $sock "WORKERS\n";

	while ( my $line = <$sock> ) {
		chomp $line;
		warn "# [$line]\n";
		last if $line eq '.';
	}
=cut

	if ( $names ne $last_names ) {
		$erase_screen = 1;
		$last_names = $names;
	}

	sleep 1;
}
