#!/usr/bin/perl -w
#
# Timer to keep track of how long I'm working on something
# Waider February 19, 2002
#
# Waider January 26 2002: Converted to Gtk, got stuck on OptionMenu. Docs, dammit.
use lib $ENV{'HOME'} . "/src/perl";
use Gtk;
use Monitor;

init Gtk;

# TODO
# Store times in worksheets with datestamps
# Better solution than popup times window
# Live update of time spent on current project

# Things I could be working on live in ~/work
my @things;

push @things, 'goofing';
opendir( DIR, $ENV{'HOME'} . "/work" );
push @things, (grep !/^\.\.?$/, readdir( DIR ));
closedir( DIR );

my %times;

package Monitor::Timer;
use POSIX;
my ( $lastchange, $current, $timeswin );

@ISA = "Monitor";

sub init {
  my $mon = shift;
  $mon->SUPER::init;
  my $opt = new Gtk::OptionMenu();# -command => sub { my $f = shift; frobmenu( $f )} )->pack();

  $mon->{'main'}->add($opt);
#  $opt->addOptions( @things );

  $mon;
}

sub frobmenu{
  my $thing = shift;
  my $now = time;

  if ( defined( $lastchange )) {
#	print strftime( "Started working on $current at %H:%M:%S, ",
#					localtime( $lastchange ));
#	print strftime( "finished at %H:%M:%S", localtime( $now ));
#	print " (" . ($now - $lastchange) . " seconds)\n";
	$times{$current} ||= 0;
	$times{$current} += $now - $lastchange;
  }

  dumptimes();

  $current = $thing;
  $lastchange = $now;
}

sub dumptimes {
  # UGLY
  if ( defined( $timeswin )) {
	eval { $timeswin->destroy() }; # might have been destroyed already
  }
  $timeswin = new MainWindow( -title => "Current Times" );
  for my $t ( keys %times ) {
	my $time = $times{$t};
	$timeswin->Label( -text => "$t: $time secs" )->pack();
  }
  $timeswin->bind( '<Button-1>', sub { $timeswin->destroy()} );
}

sub newdata {
  my $mon = shift;
  my $text = "";
  my $lasttime = $mon->{'lastrun'};

  $text = strftime( "%H:%M:%S", localtime( time ));

  $text;
}

package main;

my $mon = new Monitor::Timer;
$mon->init();
$mon->start();

Gtk->main();

