#!/usr/bin/perl
use utf8;
use Encode 'decode';
use Encode 'encode';
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use WebService::Solr;
use WebService::Solr::Query;
use warnings;
use Data::Dumper;
use YAML::XS;
use DBD::SQLite;
use DBI;
use URI::Escape;
use HTML::Template::Pro;

#
#   Libre10
#
#   Copyright 2013 yukikaze
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
my $confdata = YAML::XS::LoadFile(
	-e 'libre10.conf' ? 'libre10.conf' : '/etc/libre10.conf' );

my $sqlpath = "/tmp/libre10.db";
$sqlpath = $confdata->{dburl};
$sqldbi =
  DBI->connect( "dbi:SQLite:dbname=$sqlpath", "", "",
	{ RaiseError => 1, AutoCommit => 1 } );
my $q           = new CGI;
my $mode        = "";
my $search_text = $q->param("search_text");
$mode   = $q->param("mode");
$width  = $q->param("width");
$height = $q->param("height");
$start  = $q->param("start");
$rows   = $q->param("rows");
$fq_title_row = $q->param("fq_title");
$fq_genre_row = $q->param("fq_genre");
$fq_title = uri_unescape($fq_title_row);
#$fq_title = decode('utf-8',$fq_title);
$fq_genre = decode('utf-8',uri_unescape($fq_genre_row));
if ( $start eq "" ) { $start = "0"; }
if ( $rows  eq "" ) { $rows  = "10"; }

my $url  = $confdata->{solrurl};
my $solr = WebService::Solr->new($url);

print $q->header( -type => "text/html", -charset => "utf-8" );

$homelink = "pdfsearch.pl?mode=$mode&width=$width&height=$height&rows=$rows";
if ( $mode eq 'mobile' ) {
	$template = HTML::Template::Pro->new(
		filename          => "./template/mobile_top.tmp.html",
		die_on_bad_params => 0
	);
	$template->param( homelink => $homelink );
}
else {
	$template = HTML::Template::Pro->new(
		filename          => "./template/desktop_top.tmp.html",
		die_on_bad_params => 0
	);
}
$template->param( mode   => $mode );
$template->param( width  => $width );
$template->param( height => $height );
$template->param( start  => $start );
$template->param( rows   => $rows );
$bstart = int($start) - int($rows);
$nstart = int($start) + int($rows);

if ( $bstart < 0 ) {
	$bstart = 0;
}
$blink =
"pdfsearch.pl?mode=$mode&search_text=$search_text&width=$width&height=$height&start=$bstart&rows=$rows&fq_title=$fq_title_row&fq_genre=$fq_genre_row";
$nlink =
"pdfsearch.pl?mode=$mode&search_text=$search_text&width=$width&height=$height&start=$nstart&rows=$rows&fq_title=$fq_title_row&fq_genre=$fq_genre_row";
$template->param( blink => $blink );
$template->param( nlink => $nlink );

if ( length $search_text > 0 ) {
	$template->param( text        => $search_text );
	$template->param( show_result => "true" );
	$template->param( search_top  => "0" );
	my $query = WebService::Solr::Query->new(
		{ text => decode( 'utf-8', $search_text ) } );
	my %response_query = (
            'rows'                        => $rows,
            'start'                       => $start,
            'group.limit'                 => '30',
            'group.field'                 => 'title_group',
            'group'                       => true,
            'hl'                          => true,
            'hl.fl'                       => 'text',
            'hl.simple.pre'               => "<font color=red><em>",
            'hl.simple.post'              => "</em></font>",
            'hl.fragsize'                 => '300',
            'hl.fragmenter'               => 'gap',
            'hl.alternateField'           => 'text',
            'hl.maxAlternateFieldLength'  => '300',
            'hl.useFastVectorHighlighter' => true,
        );
	my $fq_title_solr="";
	if ((length $fq_title > 0) or (length $fq_genre > 0)){
		$sql = "SELECT title
			FROM pdffile 
			WHERE title_id = '$fq_title' 
			ORDER BY part DESC LIMIT 1";
		$dbs = $sqldbi->prepare($sql);
		$dbs->execute();
		$dbh           = $dbs->fetchrow_hashref;
		$fq_title_solr = decode('utf-8',$dbh->{'title'});
		#print Dumper $dbh;
	}
	#if ((length $fq_title > 0) and (length $fq_genre > 0)){
   # 	$response_query{'facet'} = "true";
	#	@fqs = ('title_group:$fq_title_solr','genre:$fq_genre');
	#	$response_query{'fq'} = [@fqs];
	if (length $fq_title > 0){
		$response_query{'fq'}="title_group:\"$fq_title_solr\"";
	}
	if (length $fq_genre > 0){
		$response_query{'facet'} = "true";
        @fqs = ('genre:' . $fq_genre,);
        $response_query{'fq'} = [@fqs];
	}
	#print Dumper %response_query;
	my $response = $solr->search(
		$query,\%response_query
	);
	#print Dumper $response;

	my $hits               = $response->content;
	my %hits               = %$hits;
	my $response_header    = $hits{grouped}{title_group}{groups};
	my @response_header    = @$response_header;
	my @print_group_arrays = ();
	foreach my $group (@response_header) {
		my $textarray         = $group->{doclist}{docs};
		my @textarray         = @$textarray;
		my %print_group_array = &printGroupResults(
			$group->{doclist}{numFound},
			$textarray[0]->{title_group},
			$search_text, $textarray, $response->content->{highlighting}
		);
		push( @print_group_arrays, \%print_group_array );
	}
	$template->param( group => \@print_group_arrays );
}
else {
	$template->param( search_top => true );
}

sub printGroupResults() {
	( $hitsnum, $title, $search_text, $hits, $hits_hl ) = @_;
	my $result_group;
	my @print_page_arrays = ();
	$template->param( show_result => 1 );
	foreach $doc (@$hits) {
		( $pagenum, $path, $linkpath ) =
		  ( $doc->{page}, $doc->{path_id}, $doc->{path_id} );
		my $findPageSQL =
		  "SELECT startpage,title_id from pdffile WHERE id = '$path';";
		my $sth = $sqldbi->prepare($findPageSQL);
		$sth->execute;
		$dbarray     = $sth->fetchrow_arrayref;
		$showpagenum = $pagenum + $dbarray->[0];
		$ref =
		    "title="
		  . uri_escape( $dbarray->[1] )
		  . "&pagenum=$showpagenum&mode=$mode&width=$width&height=$height";
		my %print_page_array = (
			page    => $showpagenum,
			hl_text => $hits_hl->{ $doc->{id} }{text}[0],
			refaddr => $ref
		);
		@print_page_array = ($print_page_array);
		push( @print_page_arrays, \%print_page_array );
	}
	%print_group_array = (
		text          => $title,
		search_num    => $hitsnum,
		search_result => \@print_page_arrays
	);
	return %print_group_array;
}

print $template->output();
$sqldbi . disconnect;
