#!/usr/bin/perl

use utf8;
use strict;
use warnings;
use HTTP::BrowserDetect;
use Data::Dumper;
use CGI;
use Cwd;

use lib "../scripts/modules/";
use ReaderInfo;

my $query_string = new CGI;
my $lang = $query_string->param("lang");
if (not $lang) {$lang = 'en';}

print "Content-type: text/html\n\n";
	
sub load_readers {
# Get readers metadata
  my @reader_files = <../../readers/*.json>;
  my ( %systems, %browsers );
  my ( $os, $browser, $reader_file);
  
  foreach $reader_file (@reader_files) {
    my $reader = ReaderInfo->new( $reader_file );
    
    # Sort by system
    foreach $os ( $reader->get_OS )	{
      if ( not $systems{$os} ) {$systems{$os} = [];}
      push( @{$systems{$os}}, \$reader );
    }
    
    # Sort by browser
    foreach $browser ( $reader->get_Browsers ) {
      if ( not $browsers{$browser} ) {$browsers{$browser} = [];}
      push( @{$browsers{$browser}}, \$reader );
    }
  }
  
  return (\%systems, \%browsers);
}

sub get_browsername {
  my $browser_info = shift;
  my $browser;
  my @browsers = ( 'aol', 'aol3', 'aol4', 'aol5', 'aol6', 'chrome', 'curl', 'emacs',
		   'firefox', 'gecko', 'icab', 'ie', 'ie3', 'ie4', 'ie4up', 'ie5',
		   'ie55', 'ie6', 'ie7', 'ie8', 'ie9', 'ie10', 'java', 'konqueror',
		   'lotusnotes', 'lynx', 'links', 'elinks', 'mobile_safari', 'mosaic', 'mozilla', 'neoplanet',
		   'neoplanet2', 'netfront', 'netscape', 'nav2', 'nav3', 'nav4', 'nav4up', 'nav45',
		   'nav45up', 'navgold', 'nav6', 'nav6up', 'opera', 'opera3', 'opera4', 'opera5',
		   'opera6', 'opera7', 'realplayer', 'realplayer_browser', 'safari', 'staroffice', 'webtv'
		 );

  if ($browser_info->user_agent() =~ /rekonq/i) {return "rekonq";} # special case
  foreach $browser (@browsers) {
    if (HTTP::BrowserDetect->can($browser) && $browser_info->$browser()) { return $browser;}
  }
  return '';
}

sub suggest_reader {
  my $browser_info = shift;
  my %systems = %{(shift)};
  my %browsers = %{(shift)};
  
  my @os_suggest = $systems{$browser_info->os_string()};
  my @browser_suggest = $browsers{get_browsername($browser_info)};
  
  my @reader_suggest;
  my $browser;

  if ($browser_suggest[0]) {
    foreach $browser (@{$browser_suggest[0]}){
      push(@reader_suggest, (grep { $browser == $_ } @{$os_suggest[0]}));
    }
  }

  if ( scalar(@reader_suggest) == 0 ) {return @{$os_suggest[0]};}
  else { return @reader_suggest; }
}

sub fill_template {
  my $filename = shift;
  my %replacements = %{(shift)};
  my $template_file;
  my $template_html;
  my $replacement_key;

  # Generating web output from template
  local $/;
  open( $template_file, '<'.$filename ) or die ($filename);

  while ( <$template_file> ) {
    $template_html = $_;

    foreach $replacement_key (keys %replacements) {
      $template_html =~ s/##$replacement_key##/$replacements{$replacement_key}/g;
    }
    print $template_html;
  }


}

my $browser_info = HTTP::BrowserDetect->new($ENV{"HTTP_USER_AGENT"});
my @reader_suggest = suggest_reader( $browser_info, load_readers() );

#*****
#Suggestion is working, need to work on the displaying + order reader suggest by priority
#*****

# Replacing the values
fill_template('../index/index.'. $lang .'.html',{
	      'READER_HOMEPAGE' => ${$reader_suggest[0]}->{'homepage'},
	      'READER_LOGO' => ${$reader_suggest[0]}->{'logo'},
	      'READER_NAME' => ${$reader_suggest[0]}->{'name'},
	      'READER_OS' => ${$reader_suggest[0]}->get_OS_string(),
	      'READER_LICENSE' => ${$reader_suggest[0]}->{'license'},
	      'READER_INSTALLER' => ${$reader_suggest[0]}->get_installer($browser_info->os_string()),
	      'READER_OTHER_SUGGEST' => scalar(grep {defined $_} @reader_suggest) - 1,
              });
