#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use LWP::Simple;
use HTML::TableExtract;
my %opts;

# nasza lista kategorii tvguide.com.
my @search_categories = ( qw/ action+%26+adventure adult Movie
                              comedy drama horror mystery+%26+suspense
                              sci-fi+%26+paranormal western Sports
                              Newscasts+%26+newsmagazines health+%26+fitness
                              science+%26+technology education Children%27s
                              talk+%26+discussion soap+opera
                              shopping+%26+classifieds music / );

# instrukcje dla uytkownika, ktry nie przekaza wyraenia
# ani kategorii.
sub show_usage {
 print "Naley przekaza albo szukane wyraenie (--search),\n";
 print "albo uy numeru jednej z poniszych kategorii (--category):\n\n";
 my $i=1; foreach my $cat (@search_categories) {
    $cat =~ s/\+/ /g; $cat =~ s/%26/&/; $cat =~ s/%27/'/;
    print "  $i) ", ucfirst($cat), "\n"; $i++;
 } exit;
}

# definiujemy nasze flagi wiersza polece (wersje dugie i krtkie).
GetOptions(\%opts, 'search|s=s',      # szukane wyraenie.
                   'category|c=s',    # kategoria.
); unless ($opts{search} || $opts{category}) { show_usage; }

# zmienne uywane na tvguide.com.
my ($day, $month) = (localtime)[3..4]; $month++;
my $start_time = "8:00";         # czas w formacie wojskowym
my $time_span  = 20;             # liczba godzin z programem
my $start_date = "$month\/$day"; # ustawienie aktualnego miesica i dnia
my $service_id = 61058;          # identyfikator usugi (zobacz readme tvlisting)
my $search_phrase = undef;       # ostateczne miejsce na szukane wyraenie
my $html_file = undef;           # dane pobrane z tvguide.com
my $url = 'http://www.tvguide.com/listings/search/SearchResults.asp';

# szukanie wedug kategorii.
if ($opts{category}) {
   my $id = $opts{category}; # pomocnicza.
   die "Kategoria musi by podana jako liczba!" unless $id =~ /\d+/;
   die "Niepoprawny identyfikator kategorii" unless ($id >= 1 && $id <= 19);
   $html_file = get("$url?l=$service_id&FormCategories=".
                    "$search_categories[$id-1]");
   die "get(  ) zwrcia nieoczekiwan warto.\n" unless $html_file;
   $search_phrase = $search_categories[$id-1];
}
elsif ($opts{search}) { 
   my $term = $opts{search}; # pomocnicza.
   $html_file = get("$url?I=$service_id&FormText=$term");
   die "get(  ) zwrcia nieoczekiwan warto.\n" unless $html_file;
   $search_phrase = $term;
}

# pokazujemy, co znalelimy.
print "Wyniki szukania '$search_phrase':\n\n";

# tworzymy nowy obiekt na dane z tabeli, przekazujemy
# mu nagwki tabeli tvguide.com. 
my $table_extract =
   HTML::TableExtract->new(
        headers => ["Date","Start Time", "Title", "Ch#"],
            keep_html => 1 );
$table_extract->parse($html_file);

# teraz analizujemy dane z tabeli.
foreach my $table ($table_extract->table_states) {
    foreach my $cols ($table->rows) {

        # mona byoby to zrobi lepiej...
        if(@$cols[0] =~ /Sorry your search found no matches/i)
          { print "Nic nie znaleziono!\n"; exit; }

        # pobranie daty.
        my $date = @$cols[0];
        $date =~ s/<.*>//g;       $date =~ s/\s*//g;
        $date =~ /(\w*)\D(\d*)/g; $date = "$1/$2";

        # pobranie czasu.
        my $time = @$cols[1];
        $time =~ m/(\d*:\d*\s+\w+)/;
        $time = $1;

        # get the title, detail_url, detail_number i station.
        @$cols[2] =~ /href="(.*\('\d*','(\d*)','\d*','\d*','(.*)',.*)"/i;
        my ($detail_url, $detail_num, $channel) = ($1, $2, $3);
        my $title = @$cols[2]; $title =~ s/<.*>//g;
        $title =~ /(\b(.*)\b)/g; $title = $1;

        # pobranie numeru kanau
        my $channel_num = @$cols[3];
        $channel_num =~ m/>\s*(\d*)\s*</;
        $channel_num = $1;

        # przeksztacenie zoliwego URL z Javascriptu na zwyky.
        $detail_url =~ /javascript:cu\('(\d+)','(\d+)'/;
        my $iSvcId = $1; my $iTitleId = $2;
        $detail_url = "http://www.tvguide.com/listings/".
                      "closerlook.asp?I=$iSvcId&Q=$iTitleId";

        # pokamy ju wyniki.
        print " $date o $time na chan$channel_num ($channel): $title\n";
        print "    $detail_url\n\n";
    }
}

