#!/usr/bin/perl -w

# share monitor. suitable for use in FvwmButtons, which is where I use mine.
# Waider August 2000

# Adapted from SrvMon; there's an argument for making this and that
# generic enough that you can do
#
# use Monitor::apm;
# monitors->addmonitor( Monitor::apm->new );
#
# or something.

use Tk;
use Tk::CmdLine;
use POSIX qw( strftime );
use LWP::UserAgent;

# Do X args
Tk::CmdLine::SetArguments();

my $main = new MainWindow;

$main->resizable( 0, 0 );

my $monitors = 1;
my @messages;
my @labels;

# initialise the monitors
for my $m ( 0 .. $monitors - 1 ) {
  $messages[ $m ] = "";

  # Create a label per monitor
  $labels[ $m ] = $main->Label(-wrap=>0, -textvariable => \$messages[$m],
							   -font => 'fixed', -width=>8, -height=>2)->pack;
}

my $lasttime = "??:??";
my $lastpr = 0;
newdata();

MainLoop;

sub newdata {
  $messages[ 0 ] = stepstone();
  $main->after(300000, \&newdata);
}

# example of what we're parsing:
# AC off-line, battery status high: 87%
sub stepstone {
  my $dir = "=";
  $ua = new LWP::UserAgent;
  $ua->agent( "GeekToy/0.1 " . $ua->agent );
  $ua->env_proxy();

  my $req = new HTTP::Request
	GET => 'http://no.finance.yahoo.com/q?m=OL&s=STP&d=v1';

  my $res = $ua->request( $req );

  # Check the outcome of the response
  if ($res->is_success) {
	# Yay!
	my $page = $res->content;
	# nuke
	$page =~ s/^.*?\>Ticker//si;
	$page =~ s/bgcolor="#[0-9a-f]+?"//si; # gets interpreted as a number otherwise
	my @prices = $page =~ m|[^0-9/](\d[0-9.:, ]+\d)[^0-9/]|gi;

	#push @prices, "??:??";
	#push @prices, 0;
	my $pr = 0.00;

	$time = $prices[0] || "??:??";
	if ( $time !~ /[0-9?]+[:.][0-9?]+/) {
	  # Fallback!
	  $pr = $prices[0] || 0.00;
	  $time = "??:??";
	  $req = new HTTP::Request
		GET => 'http://www.stocklink.no/bin/Server?x-service=companyInfo&security_oid=3730537';
	  $res = $ua->request( $req );
	  if ( $res->is_success ) {
		$page = $res->content;
		@prices = $page =~ m/^\s*(\d+[,:.]\d+)\s*$/mi;
		if ( @prices && $prices[ 0 ] =~ /\d+,\d+/ ) {
		  $pr = $prices[ 0 ];
		}
	  }

	  # Magic +1
	  $time = sprintf( "%02d:%02d s", ((localtime(time))[2] + 1) % 24,
					   (localtime(time))[1] );
	} else {
	  	$pr = $prices[1] || 0.00;
		$time .= " y";
	}

	$pr =~ s/,/./; # comma to decimal point

	if ( $pr > $lastpr ) {
	  $dir = "^";
	}
	if ( $pr < $lastpr ) {
	  $dir = "v";
	}
	if ( $pr > $lastpr ) {
	  $dir = "=";
	}

	$lastpr = $pr;
	$lasttime = $time;

	$line = "$pr $dir\n($time)";
  } else {
	$line = "$lastpr\n($lasttime)";
#    print $res->as_string, "\n";
  }

  $line;
}
