#!/usr/bin/perl

use LWP::UserAgent;

$base="http://www.finnkino.fi";
$url = $base."/movies/now_showing";
$ua = LWP::UserAgent->new(keep_alive => 1);
$ua->cookie_jar({});
#print STDERR "Request: $url\n";
my $response = $ua->request(HTTP::Request->new(GET => $url));
die $response->status_line unless $response->is_success;
my @lines = split /\r?\n/,$response->as_string;
my $date_count = 0;
while (@lines) {
  my $l = shift @lines;
	if ($l =~ /<option value="(\d{2}.\d{2}.\d{4})"/) {
    #print STDERR "$1\n";
		push @dates, $1;
    last if ++ $date_count == 14;
	}
}

foreach $date (@dates) {
  #print STDERR "date: $date\n";
  #print STDERR "Request: $url\n";
  %postdata = (TheatreArea=>1015, area=>1015, dt=>$date, tm=>"", genre=>"", orderBy=>alphabetical, blockID=>1006, "X-Requested-With"=>XMLHttpRequest);
  my $response = $ua->post($url, \%postdata);
  die $response->status_line unless $response->is_success;
  my @lines = split /\r?\n/,$response->as_string;
  while (@lines) {
    my $l = shift @lines;
    if ($l =~ m{<a href="http://www.finnkino.fi/Event/(\d+)/\?dt=$date">}) {
      $current_movie_url = $1;
      $movies{$current_movie_url}{sessions}{$date} = [];

      #print STDERR "Request: $current_movie_url\n";
      my $response = $ua->request(HTTP::Request->new(GET => "http://www.finnkino.fi/Event/$current_movie_url/?area=1015&dt=$date"));
      die $response->status_line unless $response->is_success;
      my $data = $response->as_string;

      unless (exists $movies{$current_movie_url}{title}) {
        my ($title) = ($data =~ m{<span class="movieName" style="font-size: 19px; line-height: 22px; font-family: Arial,sans;\s* font-weight: bold;">\s*([^<]+)</span>}m);
        $movies{$current_movie_url}{title} = &clean_text($title);
        
        my ($origtitle, $year) = ($data =~ m{<div style="color: #666666; font-size: 13px; line-height: 15px; margin-top: 2px;\s* font-style: italic;">\s* ([^\r\n]+)\s*\((\d{4})\)\s*</div>}m);
        $movies{$current_movie_url}{origtitle} = &clean_text($origtitle);
        #print STDERR "$movies{$current_movie_url}{title} $movies{$current_movie_url}{origtitle}\n";
        
        my ($genre) = ($data =~ m{Lajityyppi:\r?\n\s*([^<]+)\s*</div>}m);
        $genre =~ s{\r?\n}{ }gm;
        $genre =~ s{\s*$}{};
        my ($prod) = ($data =~ m{LevittУЄjУЄ:\r?\n\s*([^<]+)\s*</div>}m);
        $prod =~ s{\r?\n}{ }gm;
        $prod =~ s{\s*$}{};
        #my ($director) = ($data =~ m{Ohjaaja:\s*<a href="[^"]+" style="">([^<]+)</a>}m);
        my ($director) = ($data =~ m{Ohjaaja:\s*(.*?)\s*</div}ms);
        $director =~ s{<[^>]+>}{}gm;
        $director =~ s{\r?\n}{ }gm;
        $director =~ s{ {2,}}{ }gm;
        $director = &clean_text($director);
        my ($with) = ($data =~ m{ PУЄУЄosissa:\s*(.*?)\s*</div>}ms);
        $with =~ s{<[^>]+>}{}gm;
        $with =~ s{\r?\n}{ }gm;
        $with =~ s{ {2,}}{ }gm;
        $with = &clean_text($with);
        my ($duration) = ($data =~ m{ Kesto: <b>\s*(.*?)</b>}ms);
        $duration =~ s{\r?\n}{ }gm;
        $duration =~ s{ {2,}}{ }gm;
        my ($synopsis) = ($data =~ m{<div class="contboxrow">\s*<p>\s*([^\r\n]+\s*)}m);
        $synopsis =~ s{<[^>]+>}{}gm;
        $synopsis = &clean_text($synopsis);

        $desc = "Year:     $year
Genre:    $genre
Producer: $prod
Duration: $duration
Director: $director
With:     $with

$synopsis";

        $movies{$current_movie_url}{desc} .= $desc;
        #print STDERR $movies{$current_movie_url}{desc},"\n";
      }
      my $i = index($data, '<table class="t_grad">');
      my $j = index($data, '</table>', $i);
      my $session = substr($data, $i, $j-$i);
      $session =~ s{<[^>]+>}{}gm;
      $session =~ s{\r?\n}{ }gm;
      $session =~ s{ {2,}}{ }gm;
      $session =~ s{Valitse nУЄytУЖs }{}g;
      $session =~ s{\)}{)\n     }g;
      #print STDERR "$session\n";
      push @{$movies{$current_movie_url}{sessions}{$date}}, "$session";
    }
  }
}

sub date {
  my ($d, $m, $y) = split /\./, $_[0];
  return "$y$m$d";
}

sub clean_text {
  my $s = shift @_;
  $s =~ s{УЖ}{і}g;
  $s =~ s{УЄ}{ф}g;
  $s =~ s{ТЎ}{(c)}g;
  $s =~ s{т\x80Ђ}{З}g;
  $s =~ s{т\x80\x93}{--}g;
  $s =~ s{т\x80\x99}{'}g;
  $s =~ s{т\x80\x9C}{``}g;
  $s =~ s{т\x80\x9D}{''}g;
  $s =~ s{т\x80І}{...}g;
  $s =~ s{т\x82Ќ}{EUR}g;
  $s =~ s{т\x84Ђ}{TM}g;
  $s =~ s{т\x88\x92}{-}g;
  return $s;
}

sub foldlines {
  my $s = shift @_;
  my @words = split / /, $s;
  my $out = "";
  my $line = "";
  my $force_break = 0;
  while (@words) {
    my $word = shift @words;
    if ($word =~ /.+\r?\n+.+/) {
      my ($w1, $w2) = split /\r?\n/, $word, 2;
      $word = $w1;
      unshift @words, $w2;
      $force_break = 1;
    }
    if (length($word) + length($line) >= 80) {
      $out .= $line;
      $out .= "\n" unless $out =~ /\n$/;
      $line = "";
    }
    $line .= " " if $line;
    $line .= $word;
    if ($force_break) {
      $force_break = 0;
      $out .= $line;
      $out .= "\n" unless $out =~ /\n$/;
      $line = "";
    }
  }
  $out .= $line;
  return $out;
}

print "Content-type: text/xml\n\n" if exists $ENV{REQUEST_METHOD};
print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>
<rss version=\"2.0\">
  <channel>
		<title>Finnkino.fi</title>
		<link>$base</link>
		<language>fi</language>

";
my $pubdate = `date -R`;
chop($pubdate);
foreach $movie (keys %movies) {
  print "    <item>
      <title>$movies{$movie}{title} ($movies{$movie}{origtitle})</title>
      <link>http://www.finnkino.fi/Event/$movie/?area=1015</link>
      <pubDate>$pubdate</pubDate>
      <description><![CDATA[<pre>$movies{$movie}{title} ($movies{$movie}{origtitle})\n\n".
&foldlines($movies{$movie}{desc})."\n\n";

  foreach $date (sort { &date($a) <=> &date($b) } keys %{$movies{$movie}{sessions}}) {
    print "".(substr $date, 0, 5)."\n";
    foreach $s (@{$movies{$movie}{sessions}{$date}}) {
      print "     $s\n";
    }
    print "\n";
  }
  print "</pre>]]></description>
    </item>
";
}

print "  </channel>
</rss>";
