#!/usr/bin/perl
use utf8;
use Encode 'decode';
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;

#
#   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 $confpath = "";
if ( -e "libre10.conf" ) {
	$confpath = "libre10.conf";
}
else {
	$confpath = "/etc/libre10.conf";
}
$confdata = YAML::XS::LoadFile($confpath);

my $sqlpath = "/tmp/libre10.db";
$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");
my $url  = $confdata->{solrurl};
my $solr = WebService::Solr->new($url);
print $q->header( -type => "text/html", -charset => "utf-8" );
print $q->start_html(
	-title  => "rec10 pdf search",
	-lang   => "ja-JP",
	-script => { -type => "text/javascript", -src => "frame.js" },
	-style => { "src" => "libre10.css" }
);
print "<form action=\"pdfsearch.pl\" method=\"get\">";
print "<div align=center><H1>Libre10 pdf search</H1></div>";
print
"<div align=center><p><input name='search_text' value='' style='width:200px'\/>";
print "<input type=\"submit\" value=\"search\"/></p></div><hr>";

if ( length $search_text > 0 ) {
	print "<p><h3>";
	print $search_text;
	print +"の検索結果</h3></p>";
	my $query = WebService::Solr::Query->new(
		{ text => decode( 'utf-8', $search_text ) } );
	my $response = $solr->search(
		$query,
		{
			'rows'                        => '300',
			'group.limit'                 => '3000',
			'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 $response = $solr->search($query,{'rows' => '100','fl'=>'title,text,page,path'});
#my $response = $solr->search($query);
#print "texst";
	my $hits            = $response->content;
	my %hits            = %$hits;
	my $response_header = $hits{grouped}{title_group}{groups};
	my @response_header = @$response_header;

	foreach my $group (@response_header) {
		my $textarray = $group->{doclist}{docs};
		my @textarray = @$textarray;
		&printGroupResults(
			$group->{doclist}{numFound},
			$textarray[0]->{title_group},
			$search_text, $textarray, $response->content->{highlighting}
		);
	}
}
else {
	print "<div align=center>";
	print
"<a href=pdfsearch.pl?mode=mobile&width=1024&height=1280>for narrow band</a><br>\n";
	print
"<a href=pdfsearch.pl?mode=mobile&width=1600&height=2560>for Tablet</a><br>\n";

	print
"<a href=pdfsearch.pl?mode=mobile&width=1080&height=1920>for SmartPhone</a><br>\n";
	print
"<a href=pdfsearch.pl?mode=mobile&width=1600&height=2100>for Tablet retina</a><br>\n";
	print
"<a href=pdfsearch.pl?mode=mobile&width=1280&height=2400>for SmartPhone retina</a><br>\n";
	print "<a href=pdfsearch.pl?mode=''>for PC(default)</a><br>\n";
	print "</div>";
}
print "<input type='hidden' name='mode'   value=" . $mode . " >\n";
print "<input type='hidden' name='height' value=" . $height . " >\n";
print "<input type='hidden' name='width'  value=" . $width . " >\n";

print "</form>";
print $q->end_html;

sub printGroupResults() {
	( $hitsnum, $title, $search_text, $hits, $hits_hl ) = @_;
	print "<p><h2>$title</h2>  -  $hitsnum 件の合致<br>";
	foreach $doc (@$hits) {
		( $pagenum, $path, $linkpath ) =
		  ( $doc->{page}, $doc->{path_id}, $doc->{path_id} );
		my $findPageSQL = "SELECT startpage from pdffile WHERE id = '$path';";
		my $sth         = $sqldbi->prepare($findPageSQL);
		$sth->execute;
		$showpagenum = $pagenum + $sth->fetchrow_array;
		print "page " . $showpagenum . "<br>";
		print "　" . $hits_hl->{ $doc->{id} }{text}[0] . "<br>";
		print "<a href=\"htmlserver.pl?pdfpath=$path";
		print "&pagenum=$pagenum&mode=$mode&width=$width&height=$height\">";
		print "該当ページを見る";
		print "</a>";
		print "</p>\n";
	}
}

$sqldbi . disconnect;
