#!/usr/bin/perl -w

=pod

=head1 NAME

tv_to_text - Convert XMLTV listings to text.

=head1 SYNOPSIS

tv_to_text [--help] [--with-desc] [--output FILE] [FILE...]

=head1 DESCRIPTION

Read XMLTV data and output a summary of listings.  The programme titles,
subtitles, times and channels are shown.

B<--with-desc> include programme description in output

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

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

Ed Avis, ed@membled.com

=cut

use strict;
use warnings;
use XMLTV qw(best_name);
use XMLTV::Version "$XMLTV::VERSION";
use IO::File;
use Date::Manip;
use Getopt::Long;

BEGIN {
    if (int(Date::Manip::DateManipVersion) >= 6) {
	Date::Manip::Date_Init("SetDate=now,UTC");
    } else {
	Date::Manip::Date_Init("TZ=UTC");
    }
}

# 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();
    }
}

use XMLTV::Summarize qw(summarize);
use XMLTV::Usage <<END
$0: convert listings to plain text
usage: $0 [--help] [--with-desc] [--output FILE] [FILE...]
END
;

my ($opt_help, $opt_output, $opt_withdesc);
GetOptions('help' => \$opt_help, 'output=s' => \$opt_output, 'with-desc' => \$opt_withdesc) or usage(0);
usage(1) if $opt_help;
@ARGV = ('-') if not @ARGV;
if (defined $opt_output) {
    open(STDOUT, ">$opt_output")
      or die "cannot write to $opt_output: $!";
}
$opt_withdesc = 0 if !defined $opt_withdesc;

# FIXME maybe memoize some stuff here

my ($encoding, $credits, $ch, $progs) = @{XMLTV::parsefiles(@ARGV)};
my $wrote_prog = 0;
foreach (summarize($ch, $progs)) {
    if (not ref) {
	print "\n" if $wrote_prog;
	print "$_\n\n";
	next;
    }
    my ($start, $stop, $title, $sub_title, $channel, $desc) = @$_;
    $stop = '' if not defined $stop;
    $title .= " // $sub_title" if defined $sub_title;
    print "$start--$stop\t$title\t$channel". ( $opt_withdesc && defined $desc ? "\t$desc" : '' ) . "\n";
    $wrote_prog = 1;
}

# Acknowledgements
my $g = $credits->{'generator-info-name'};
$g =~ s!/(\d)! $1! if defined $g;
my $s = $credits->{'source-info-name'};
if (not defined $g and not defined $s) {
    # No acknowledgement since unknown source.
}
elsif (not defined $g and defined $s) {
    print "\nGenerated from $s.\n";
}
elsif (defined $g and not defined $s) {
    print "\nGenerated by $g.\n";
}
elsif (defined $g and defined $s) {
    print "\nGenerated from $s by $g.\n";
}
else { die }
