#!/usr/bin/perl

use warnings;
use strict;

use Frikanalen;
use XML::Simple;
use POSIX;
use Date::Parse;
use Data::Dumper;
use Getopt::Std;

my %opts;

getopts("do:", \%opts);

my $debug = $opts{d} || 0;

my $targetorg = $opts{o} || '';

my $listref = Frikanalen::getEpgUrls();
for my $url (@{$listref}) {
    print "Loading '$url'\n" if $debug;
    my $ua = new LWP::UserAgent;
    my $req = new HTTP::Request GET => $url;
    my $res = $ua->request($req);
    my $epgref = XMLin($res->content);
    my $lastday = "";
    for my $event (@{$epgref->{event}}) {
        next if ($targetorg && $targetorg ne ($event->{organisation} || ""));

        print Dumper($event) if $debug;
        my $title = $event->{title};
        my $org = $event->{organisation} || '[ukjent/privat]';
        my $category = $event->{category};

        my $start = $event->{start};
        my $starttime = str2time($start);
        my $startstring = strftime("%H:%M", localtime($starttime));

        my $stop = $event->{stop};
        my $stoptime = str2time($stop);
        my $stopstring = strftime("%H:%M", localtime($stoptime));

        my $daystring = strftime("%Y-%m-%d", localtime($starttime));
        if ($lastday ne $daystring) {
            print "\n$daystring\n";
            $lastday = $daystring;
        }
        print "  $startstring-$stopstring $title;$org;$category\n";
    }
}
