#!/usr/bin/perl

=pod

=head1 NAME

tv_grab_pt - Grab TV listings for Portugal.

=head1 SYNOPSIS

tv_grab_pt --help

tv_grab_pt [--config-file FILE] --configure [--gui OPTION]

tv_grab_pt [--config-file FILE] [--output FILE] [--quiet]

tv_grab_pt --list-channels

=head1 DESCRIPTION

Output TV listings for several channels available in Portugal.
It supports the public network and the private NetCabo network.

First run B<tv_grab_pt --configure> to choose, which channels you want
to download. Then running B<tv_grab_pt> with no arguments will output
listings in XML format to standard output.

B<--configure> Prompt for which channels,
and write the configuration file.

B<--gui OPTION> Use this option to enable a graphical interface to be used.
OPTION may be 'Tk', or left blank for the best available choice.
Additional allowed values of OPTION are 'Term' for normal terminal output
(default) and 'TermNoProgressBar' to disable the use of Term::ProgressBar.

B<--config-file FILE> Set the name of the configuration file, the
default is B<~/.xmltv/tv_grab_pt.conf>.  This is the file written by
B<--configure> and read when grabbing.

B<--output FILE> write to FILE rather than standard output.

B<--quiet> suppress the progress messages normally written to standard
error.

B<--help> print a help message and exit.

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

Bruno Tavares, gawen@users.sourceforge.net, based on tv_grab_es, from Ramon Roca.

=head1 BUGS

=cut

######################################################################
# initializations

use warnings;
use strict;
use XMLTV::Version '$Id: tv_grab_pt,v 1.9 2005/01/23 21:39:27 epaepa Exp $ ';
use Getopt::Long;
use Date::Manip;
use Data::Dumper;
use HTML::TreeBuilder;
use HTML::Entities; # parse entities
use IO::File;
use File::Path;
use File::Basename;

use XMLTV;
use XMLTV::Memoize;
use XMLTV::ProgressBar;
use XMLTV::Ask;
use XMLTV::Config_file;
use XMLTV::DST;
use XMLTV::Get_nice;
use XMLTV::Mode;
# Todo: perhaps we should internationalize messages and docs?
use XMLTV::Usage <<END
$0: get Portuguese television listings in XMLTV format
To configure: $0 --configure [--config-file FILE] [--gui OPTION]
To grab listings: $0 [--config-file FILE] [--output FILE] [--quiet]
To list channels: $0 --list-channels
END
  ;

# Attributes of the root element in output.
my $HEAD = { 'source-info-url'     => 'http://tvcabo.pt',
	     'source-data-url'     => "http://tvcabo.pt/tv_cabo_progr_canal.asp",
	     'generator-info-name' => 'XMLTV',
	     'generator-info-url'  => 'http://membled.com/work/apps/xmltv/',
	   };

# default language
my $LANG="pt";

# Global channel_data
our @ch_all;

######################################################################
# get options

# Get options, including undocumented --cache option.
XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');
my ($opt_help, $opt_output,
    $opt_configure, $opt_config_file, $opt_gui, $opt_quiet,
    $opt_list_channels);
$opt_quiet  = 0; # default
GetOptions('help'          => \$opt_help,
	   'configure'     => \$opt_configure,
	   'config-file=s' => \$opt_config_file,
	   'gui:s'         => \$opt_gui,
	   'output=s'      => \$opt_output,
	   'quiet'         => \$opt_quiet,
	   'list-channels' => \$opt_list_channels,
	   'offset=i'      => \ my $opt_offset,        # ignored
           'days=i'        => \ my $opt_days,          # ignored
	  )
  or usage(0);
usage(1) if $opt_help;
XMLTV::Ask::init($opt_gui);

# --offset and --days are ignored (we return more data than was
# requested) but at least check the user didn't ask for something
# impossible.
#
my $first_day = ($opt_offset || 0) + ($opt_days || 0);
die 'cannot grab more than one week ahead' if $first_day >= 7;
warn "ignoring --offset\n" if defined $opt_offset;
warn "ignoring --days\n" if defined $opt_days;

my $mode = XMLTV::Mode::mode('grab', # default
			     $opt_configure => 'configure',
			     $opt_list_channels => 'list-channels',
			    );

# File that stores which channels to download.
my $config_file
  = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_pt', $opt_quiet);

my @config_lines; # used only in grab mode
if ($mode eq 'configure') {
    XMLTV::Config_file::check_no_overwrite($config_file);
    mkpath(dirname($config_file));
}
elsif ($mode eq 'grab') {
    @config_lines = XMLTV::Config_file::read_lines($config_file);
}
elsif ($mode eq 'list-channels') {
    # Config file not used.
}
else { die }

# Whatever we are doing, we need the channels data.
my %channels = get_channels(); # sets @ch_all
my @channels;

######################################################################
# write configuration

if ($mode eq 'configure') {
    open(CONF, ">$config_file") or die "cannot write to $config_file: $!";

    # Ask about each channel.
    my @chs = sort keys %channels;
    my @names = map { $channels{$_} } @chs;
    my @qs = map { "add channel $_?" } @names;
    my @want = ask_many_boolean(1, @qs);
    foreach (@chs) {
	my $w = shift @want;
	warn("cannot read input, stopping channel questions"), last
	  if not defined $w;
	# No need to print to user - XMLTV::Ask is verbose enough.

	# Print a config line, but comment it out if channel not wanted.
	print CONF '#' if not $w;
	my $name = shift @names;
	print CONF "channel $_.tvcabo.pt\n";
    }

    close CONF or warn "cannot close $config_file: $!";
    say("Finished configuration.");

    exit();
}


# Not configuration, we must be writing something, either full
# listings or just channels.
#
die if $mode ne 'grab' and $mode ne 'list-channels';

# Options to be used for XMLTV::Writer.
my %w_args;
if (defined $opt_output) {
    my $fh = new IO::File(">$opt_output");
    die "cannot write to $opt_output: $!" if not defined $fh;
    $w_args{OUTPUT} = $fh;
}
$w_args{encoding} = 'ISO-8859-1';
my $writer;
sub start_writing() { ($writer = new XMLTV::Writer(%w_args))->start($HEAD) }

if ($mode eq 'list-channels') {
    start_writing;
    $writer->write_channel($_) foreach @ch_all;
    $writer->end();
    exit();
}

######################################################################
# We are producing full listings.
die if $mode ne 'grab';

# Read configuration
my $line_num = 1;
foreach (@config_lines) {
    ++ $line_num;
    next if not defined;

    # For now, check that tvcabo.pt appears on every line.  This
    # ensures we don't have a config file left over from the old
    # grabber.
    #
    if (/^channel:?\s+(\d+).tvcabo.pt\s*$/) {
	my $ch_did = $1;
	die if not defined $ch_did;
	push @channels, $ch_did;
    }
    elsif (/^channel/) {
	die <<END
The configuration file is left over from the old tv_grab_pt.  The new
site uses different channels so you need to reconfigure the grabber.
END
  ;
    }
    else {
	warn "$config_file:$line_num: bad line\n";
    }
}

######################################################################
# begin main program

start_writing;

# Assume the listings source uses CET (see BUGS above).
die "No channels specified, run me with --configure\n"
  if not keys %channels;
my @to_get;

# the order in which we fetch the channels matters
# This progress bar is for both downloading and parsing.  Maybe
# they could be separate.
#

my $bar = new XMLTV::ProgressBar('getting listings',
				scalar @channels)
  if not $opt_quiet;
foreach my $ch_did (@channels) {
    die if not defined $ch_did;
    my $ch_name=$channels{$ch_did};
    $writer->write_channel({ id => $ch_did.'.tvcabo.pt',
                             'display-name' => [ [ $ch_name ] ] });
}


my $some=0;
foreach my $ch_did (@channels) {
	foreach (process_table($ch_did)) {
	    $writer->write_programme($_);
	    $some = 1;
	}
	update $bar if $bar;
}
if (not $some) {
  die "no programmes found\n" unless $some;
}

$writer->end();

######################################################################
# subroutine definitions

# Use Log::TraceMessages if installed.
BEGIN {
    eval { require Log::TraceMessages };
    if ($@) {
	*t = sub {};
	*d = sub { '' };
    }
    else {
	*t = \&Log::TraceMessages::t;
	*d = \&Log::TraceMessages::d;
	Log::TraceMessages::check_argv();
    }
}

# Clean up bad characters in HTML.
sub tidy( $ ) {
    for (my $s = shift) {
	# Character 150 seems to be used for 'versus' in sporting
	# events, but I don't know what that is in Portuguese.
	#
	s/\s\226\s/ vs /g;
	return $_;
    }
}

sub process_table {
    my ($ch_xmltv_id) = @_;

    t "Getting channel $ch_xmltv_id\n";

    my $url = $HEAD->{'source-data-url'}."?identificadorCanal=$ch_xmltv_id&l1.x=1&l1.y=2";
    #print STDERR "Getting url : $url"; 
    t $url;
    my $data=tidy(get_nice($url));
    if (not defined $data) {
	die "could not fetch $url, aborting\n";
    }
    local $SIG{__WARN__} = sub {
	warn "$url: $_[0]";
    };

    # parse the page to a document object
    my $tree = HTML::TreeBuilder->new();
    $tree->parse($data);
    my @program_data = get_program_data($tree);
    if (not @program_data) {
	warn "$url: no programmes found\n";
	return ();
    }

    my $first = $program_data[0];
    my @r;
    foreach my $p (@program_data) {
	push @r, make_programme_hash($ch_xmltv_id, $p, $first);
    }
    return @r;
}

sub make_programme_hash {
    my ($ch_xmltv_id, $cur, $first) = @_;

    my $date = $cur->{date};

    my %prog;

    $prog{channel}       =$ch_xmltv_id.'.tvcabo.pt';
    $prog{title}         =[ [ $cur->{title}, $LANG ] ];
    $prog{"sub-title"}   =[ [ $cur->{subtitle}, $LANG ] ] if $cur->{subtitle};
    $prog{category}      =[ [ $cur->{category}, $LANG ] ] if $cur->{category};
    $prog{"episode-num"} = $cur->{"episode-num"} if $cur->{"episode-num"};


    if ( ($cur->{time} < $first->{time}) && ($cur->{date} == $first->{date}) ) {
	t "Jumping for next day of (".$cur->{time}.",".$first->{time}.") $date...";
	$date = nextday($date);
	t "Got $date\n";
    }

    my $time = $date.$cur->{time}."00";

    #print STDERR "Date built = $time\n";

    $prog{start}=utc_offset($time, '+0000');
    t "...got $prog{start}";
    unless ($prog{start}) {
	warn "bad time string: $cur->{time}";
	return undef;
    }

    $prog{desc}=[ [ $cur->{desc}, $LANG ] ] if $cur->{desc};
	
    return \%prog;
}


# as_trimmed_text() doesn't deal with ASCII 160, non-breaking space.
sub trim( $ ) {
    for (my $tmp = shift) {
	tr/\240/ /;
	s/^\s+//;
	s/\s+$//;
	return $_;
    }
}

#
sub get_program_data {
    my ($tree) = @_;

    my @data;

    my %month_conv = (
		'Jan' => 'Jan',
		'Fev' => 'Feb',
		'Mar' => 'Mar',
		'Abr' => 'Apr',
		'Mai' => 'May',
		'Jun' => 'Jun',
		'Jul' => 'Jul',
		'Ago' => 'Aug',
		'Set' => 'Sep',
		'Out' => 'Oct',
		'Nov' => 'Nov',
		'Dez' => 'Dec',
    );

    my @tables = $tree->find_by_tag_name("_tag"=>"table");


    # Actually time and title are required, but we don't check that.
    my $table_n = 0;
    foreach my $table (@tables) {
	my @trs = $table->find_by_tag_name("_tag"=>"tr");
	next unless $trs[2];
	my @tds = $trs[2]->find_by_tag_name("_tag"=>"td");
	next unless (scalar(@tds) == 1);
	my $should_be_hour = trim($tds[0]->as_trimmed_text())."\n";
	next unless ($should_be_hour =~ /.* - (\d+) de (.*) de (\d+)/);
	#print STDERR "\n*".$should_be_hour."*\n";
	my ($day, $month, $year) = ($1, $2, $3);
	$month =~ s/^(\w{3}).*$/$1/;
	$month = $month_conv{$month};
	
	#print STDERR "Parsed date to $day, $month, $year -> ".ParseDate("$day $month $year")."\n";
	my $parsed_date = ParseDate(sprintf("%02d %3s %04d",$day, $month, $year));
	die "Parse error, could not parse date" unless $parsed_date;
	my $f_date = $parsed_date;
	$f_date =~ s/^(\d{4})(\d{2})(\d{2}).*/$1$2$3/; 
	#print "Final date found : $f_date\n";
	#print "--- $f_date matched\n";

	my $index = 3;
	while ($trs[$index]) {
		my @tds = $trs[$index]->find_by_tag_name("_tag"=>"td");
		last unless( $tds[0] && $tds[1] );
		my $time = trim($tds[0]->as_trimmed_text());
		my $title = trim($tds[1]->as_trimmed_text());
		my $sub_t = "";
		my $episode = "";

		if ( my $i =  $tds[1]->find_by_tag_name("_tag"=>"i") ) {
			my $tmp = trim($i->as_trimmed_text());	
			$tmp =~ s/\(/\\\(/g;
			$tmp =~ s/\)/\\\)/g;
			$title =~ s/$tmp//;
			$tmp =~ s/^\s*?(.*?)\s*?/$1/;
			if ($tmp =~ /(Epis..io\s+\d+)/) {
				my $ep = $1;
				$tmp =~ s/$ep//;
				$ep =~ s/^Epis..io\s+//;
				$episode = "";

			}
			if ($tmp) {
				$sub_t = $tmp;
			}
		}	

		$time =~ s/://g;
		#print STDERR "Found $time | $title\n";

		for ($title) { s/^\s+$//; s/\s+$// }
                my %h = (       time =>         $time,
                                title=>         $title,
				date =>         $f_date,
				"episode-num" =>      $episode,
                                subtitle=>      $sub_t,
                                desc =>         "");
                push @data, \%h;
        	$index = $index + 1;
	}
    }
    return @data;
}

# get channel listing
sub get_channels {
    my $bar = new XMLTV::ProgressBar('getting list of channels', 1)
	if not $opt_quiet;
    my %channels;
    my $url=$HEAD->{'source-data-url'};
    t $url;
    my $local_data=get_nice($url);
    die "could not get channel listing $url, aborting\n"
      if not defined $local_data;

    my $tree = HTML::TreeBuilder->new();
    $tree->parse($local_data);
    my @menus = $tree->find_by_tag_name("_tag"=>"select");
    
    foreach my $elem (@menus) {
	my $cname = $elem->attr('name');
	next unless $cname eq 'identificadorCanal';	
        my @ocanals = $elem->find_by_tag_name("_tag"=>"option");
        @ocanals = sort @ocanals;
	foreach my $opt (@ocanals) {
		    my $channel_id  = $opt->attr('value');
		    my $channel_name= trim($opt->content->[0]);
		    $channels{$channel_id}=$channel_name;
		    push @ch_all, { 'display-name' => [ [ $channel_name,
							  $LANG ] ],
				    'id'=> "$channel_id" };
	} #foreach
    } #while
    die "no channels could be found" if not keys %channels;
    update $bar if not $opt_quiet;
    return %channels;
}

sub nextday {
    my $d = shift;
    my $p = ParseDate($d);
    my $n = DateCalc($p, '+ 1 day');
    return UnixDate($n, '%Q');
}
