#
# TV::Format - format info for display
# ~~~~~~~~~~   (c) Andrew Flegg 2002. Released undr the Artistic Licence.

package TV::Format;

use TV::Core;
use HTML::Entities;

my %_DAYS = ();

# -- We're created -----------------------------------------------------
#
sub new {
    my $class   = shift;
    my (%parm)  = @_;
    my $self    = bless \%parm, $class;

    my $day     = int($self->{day} || 0);
    my $channel = $self->{channel} or die "No channel specified\n";

    if (!$self->{listings}) {
        my $file    = "$day/$channel.xml";
        my $datadir = $TV::Core::DATA_DIR.'/listings';
        return undef unless -f "$datadir/$file";

        open(IN, "<$datadir/$file") or die "Unable to read $file: $!\n";
        my %temp          = ();
        $self->{listings} = [];
        while(<IN>) {
            if (m!<channel id="$channel" source="([^"]*?)"!) {
                $self->{source} = $1;

            } elsif (m!</programme>!) {
                my %entry       = %temp;
                %temp           = ();
                $entry{pid}     = scalar(@{ $self->{listings} }) + 0;
                $entry{day}     = $day;
                $entry{channel} = $channel;
                push @{ $self->{listings} }, \%entry if %entry;

            } elsif (m!<(\w+)>(.*)</\1>!) {
                my ($k, $v) = ($1, $2);

                $temp{$k} = decode_entities($v);
            }
        }
        close(IN);
    }

    return $self;
}


# -- Get a day name ----------------------------------------------------
#
sub getDayName {
    my $class = shift;
    my $day   = shift;

    return $_DAYS{$day} if $_DAYS{$day};

    use POSIX qw(strftime);
    my @date  = @_ || localtime();
    $date[3] += $day;
    $date[6]  = -1;
 
    return $_DAYS{$day} = strftime('%A', @date);
}
    

# -- Get a formatted time ----------------------------------------------
#
sub getTime {
    my $self  = shift;
    my $entry = shift;

    my ($sh, $sm) = (int($entry->{start} / 100), ($entry->{start} % 100));
    my ($eh, $em);

    if ($entry->{end}) {
        ($eh, $em) = (int($entry->{end} / 100), ($entry->{end} % 100));

    } elsif ($entry->{duration}) {
        use Date::Calc;
        my @start = (Date::Calc::Today(), $sh, $sm, 00);
        my @end   = Date::Calc::Add_Delta_DHMS(@start, 0, 0,
                                               $entry->{duration}, 0);
        ($eh, $em) = $lastend[3..4];

    } else {
        ($eh, $em) = ($sh, $sm);
    }

    my $start = substr("0$sh", -2).':'.substr("0$sm", -2);
    my $end   = substr("0$eh", -2).':'.substr("0$em", -2);
    $end      = 'close' if $start eq $end;
    return ($start, $end);
}


# -- Get a formatted title ----------------------------------------------
#
sub getTitle {
    my $self  = shift;
    my $entry = shift;
    my $title = $entry->{title};

    if ($entry->{type}
     &&(($entry->{type} eq 'Film') || ($entry->{type} eq 'TVM'))) {
        my $str = $title;
        my $yr  = $entry->{year} || '';
        $str    =~ s/^The (.*)$/$1, The/;
        $str    =~ s/[^A-Za-z0-9 ]//g;
        $str    =~ s/([^A-Za-z0-9])/"%".unpack("H*",$1)/eg;

        my $url = "http://uk.imdb.com/Tsearch?title=$str&type=substring";
        $url   .= "&from_year=".($yr-1)."&to_year=".($yr+1) if $yr;
        $title  = "<a href=\"$url\">$title</a>";
    }

    return $title;
}


# -- Get a formatted subtitle/episode name -----------------------------
#
sub getSubtitle {
    my $self     = shift;
    my $entry    = shift;
    my $subtitle = '';

    if ($entry->{subtitle}) {
        my $ep  = $entry->{subtitle};
        my $tit = $entry->{title};
        my $str = "\"$tit\" \"$ep\"";
        $str    =~ s/([^A-Za-z0-9])/"%".unpack("H*",$1)/eg;

        my $url = "http://www.google.com/search?safe=on&q=$str";
#                  "&btnI=I'm+Feeling+Lucky";
        $subtitle = "<a href=\"$url\">$ep</a>";

    } elsif ($entry->{type}
          &&(($entry->{type} eq 'Film') || ($entry->{type} eq 'TVM'))) {
        $subtitle  = $entry->{type};
        $subtitle .= ' ('.$entry->{year}.')' if $entry->{year};
        $subtitle .= ' ['.$entry->{rating}.']' if $entry->{rating};
    }

    return $subtitle;
}


# -- Get a formatted description ---------------------------------------
#
sub getDescription {
    my $self  = shift;
    my $entry = shift;

    return $entry->{desc} || '';
}


# -- Get flags ----------------------------------------------------------
#
sub getFlags {
    my $self  = shift;
    my $entry = shift;

    return $entry->{flags} || '';
}


# -- Get a link for more information ------------------------------------
#
sub getInfoLink {
    my $self  = shift;
    my $entry = shift;
    my $ua    = $ENV{'HTTP_USER_AGENT'} || '';

    return '' unless $entry->{infourl};
    return '<!-- bad robot -->' if $ua =~ /(AvantGo|MSIECrawler)/;

    my $url = 'info.html?ch='.$entry->{channel}.'&day='.$entry->{day}.
                      '&pid='.$entry->{pid};
    $url   .= '&all' if ($ENV{'QUERY_STRING'} || '') =~ /\ball\b/;
    return "<a class=\"infourl\" href=\"$url\" title=\"More info...\">&gt;&gt;</a>";
}


# -- Get the URL containing more info -----------------------------------
#
sub getInfoURL {
    my $self  = shift;
    my $entry = shift;

    return $entry->{infourl} || '';
}


# -- Get background colours ---------------------------------------------
#
sub getColour {
    my $self  = shift;
    my $entry = shift;
    my $user  = shift;

    return 'dddddd' if $entry->{type} && $entry->{type} eq 'Film';
    return '';
}

1;
