#!/usr/bin/perl -w

=head1 NAME

list-train-times - extract info from http://jp.transinfo.qld.gov.au/

=head1 SYNOPSIS

list-train-times [ --to Station ] [ --from Station ] [ --w3m ] [ --nosummary ]

list-train-times [ --man | --help ]

=head1 DESCRIPTION

B<This program> extracts data from the TransInfo Journey Planner
website, http://jp.transinfo.qld.gov.au/, and either sends it to
w3m for a pretty display or produces a short summary, for example,

    $ list-train-times
    Trains Dutton Park to Central after 8:00pm
     8:07pm Ferny Grove
     8:37pm Ferny Grove
     9:07pm Ferny Grove
     9:37pm Ferny Grove

=head1 OPTIONS

=over 8

=item B<--from=<station>>
=item B<--to=<station>>

Override the internal guesswork with stations on the Queensland Rail network.

=item B<--w3m>

Send the results page through to w3m for a pretty display.

=item B<--nosummary>

Do not produce the summary.

=item B<--man>

Print the manual page and exit.

=item B<--help>

Print a brief help message and exit.

=back

=head1 EXIT CODES

If B<this program> exits with a zero exit status and the correct
output is on standard output.  Nothing else is ever printed to
standard output.

B<This program> will exit with a non-zero exit status if there
was a fatal error.  Both fatal and non-fatal errors will cause
output on standard error.

=head1 VERSION

    $Id: list-train-times,v 1.2 2008/05/17 07:00:42 suter Exp $

=head1 AUTHOR and COPYRIGHT

Copyright (C) 2003 Mark Suter E<lt>F<suter@humbug.org.au>E<gt>

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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
or from the following webpage.

    http://www.gnu.org/licenses/gpl.txt

=cut

use strict;
use WWW::Mechanize;
use HTML::TableExtract;
use Getopt::Long;
use Pod::Usage;

## Pick the trip, based on time
my ($type, $hour) = ("Railway Station", (localtime)[2]);
my ($src, $dst) =
    $hour <= 11 ? ("Dutton Park", "Roma Street") :	#      -> 11am
    $hour <= 14 ? ("Roma Street", "Central") :		# 11am -> 2pm
    $hour >= 19 ? ("Dutton Park", "Central") :		#  7pm ->
	          ("Roma Street", "Dutton Park");	#  2pm -> 7pm

## Process options
my %opt = (man => 0, help => 0, w3m => 0, summary => 1, to => undef, from => undef);
GetOptions(\%opt, "man", "help", "w3m", "summary!", "to=s", "from=s") or pod2usage(0);
$opt{man} and pod2usage(-exitval => 0, -verbose => 2);
$opt{help} and pod2usage(0);

## Override stations
defined $opt{to} and $dst = $opt{to};
defined $opt{from} and $src = $opt{from};

## Get my timetable
my $ua = WWW::Mechanize->new(autocheck => 1, quiet => 1, keep_alive => 32);
$ua->agent_alias('Windows IE 6');
$ua->get('http://jp.transinfo.qld.gov.au/TransLinkJP.asp');
{
    ## Hide "<input> outside <form>" warning
    local $^W = 0;
    $ua->submit_form(fields => {Vehicle => "Train", FromSuburb => "$src $type", ToSuburb => "$dst $type"});
}

## Dump to w3m
$opt{w3m} and do {
    open W3M, "| w3m -T text/html" or die "$0: can't fork: $!\n";
    print W3M $ua->content or die "$0: can't print: $!\n";
    close W3M or die "$0: can't close: $!\n";
};

## A five (or so) line summary
$opt{summary} and do {
    printf "Trains $src to $dst after %s\n", map lc, $ua->content =~ /Leave After.+?(\d+:\d+(AM|PM))/i;
    my $te = new HTML::TableExtract(count => 1, depth => 2)->parse($ua->content);
    my ($train, $time) = qw(blank blank);
    foreach my $ts ($te->table_states) {
	foreach my $row ($ts->rows) {
	    $row->[1] =~ /Take Train/i and $row->[3] =~ /Route\s+[A-Z]{4}\s*-.*?to\s*([[:print:]]+)/i and $train = $1;
	    $row->[1] =~ /Departing/i and $row->[2] =~ /(\d+:\d+(AM|PM))/i and $time = $1;
	    $row->[1] =~ /Arriving/i and printf "%7s %s\n", $time, $train;
	}
    }
};

## Notice weird things like "no space on device"
END { close STDOUT or die "$0: can't close stdout: $!\n" }

