#!/usr/bin/perl -w

my $VERSION;
$VERSION="2.1";


use strict;
use warnings;

use Image::Magick;
use DBI;
use Getopt::Long;
use fontlinge::Filebasics;
use fontlinge::Fontling;

#print *create_spread , "\n" ;
#exit;




no utf8;
use bytes;

my %config;

my $dbh;
my $sth;
my $font;
my $tmp_font;
my $max_width =1024;
my $max_height=1024;
my $subline_distance=10;
my $subline_fontsize=12;
my $subline_font ="";
my $y_gap=15;
my $x_gap=15;
my $x_rgap=0;
my $strokewidth=3;
my $list_fonts;
my $list_categories;
my $help;
my $my_preview_suffix;
my $my_code;

my ($query, $order);
GetOptions (	'query=s'		=> \$query ,
		'order=s'		=> \$order ,
		'width:i' 		=> \$max_width ,
		'height:i' 		=> \$max_height ,
		'subline-distance:i'	=> \$subline_distance ,
		'subline-fontsize:i'	=> \$subline_fontsize ,
		'subline-font:s'	=> \$subline_font ,
		'y-gap:i'		=> \$y_gap ,
		'x-gap:i'		=> \$x_gap ,
		'my-preview-suffix|my_preview_suffix=s'	=> \$my_preview_suffix,
		'x-rgap:i'		=> \$x_rgap ,
		'strokewidth:i'		=> \$strokewidth,
		'list-fonts'		=> \$list_fonts,
		'list-categories'	=> \$list_categories,
 		'my-code=s'		=> \$my_code,
		'help'			=> \$help
) || exit -1 ;



if (defined $help) {
	&help();
	exit;
}



%config=fontlinge_Get_Config();

# implement userdefined code
#
if( ! $my_code && $config{'my_code' } ) { 
	$my_code = $config{'my_code'};
}
if( $my_code ) { 
	$my_code = fontlinge_My_Path( $my_code ,$config{'my_code' }, 'my_code' ); # cleanup the path
print "fontlinge_montage: " ,  *create_spread , "\n";
	fontlinge_My_Code( $my_code );	# overwrite subroutines with MY_* subs
#print "xxx\n";
#	exit;
}



if (defined $list_fonts) {
	my $image = new Image::Magick;
	print join("\n",$image->QueryFont());
	print "\n";
	exit;
}



$dbh = fontlinge_Open_Database (
	$config{'username'},
	$config{'password'},
	$config{'mysqlserver'},
	$config{'database'}
);

if (defined $list_categories) {
	$sth = $dbh->prepare("SELECT kategorie_name,kategorie_id FROM kategorien ORDER BY kategorie_name");
	$sth->execute();
	while($font = $sth->fetchrow_hashref) {
		print $font->{'kategorie_id'}."\t";
		print $font->{'kategorie_name'}."\n";
	}
	print "\n";
	exit;
}

if ( $subline_font eq "") {
	my $image = new Image::Magick;
	my @fonts = $image->QueryFont();
	$subline_font= $fonts[0];
	undef @fonts;
	undef $image;
}


if ( ! defined $query) {$query='1';}
if ( $query eq '') {$query='1';}
if ( ! defined $order) {$order='1';}
if ( $order eq '') {$order='1';}

$query="SELECT font_id,font_path,font_name,font_datatype,font_filetype,font_kategorie,font_complete FROM fonts WHERE $query ORDER BY $order";
$sth = $dbh->prepare($query);
$sth->execute();

my $image_name;
my $wrn;
my $image;
my $klein;
my $x;
my $y;
my ($w, $h);
my $spread_nr=0;
my $there_is_content;

&create_spread;

$font	=	new fontlinge::Fontling();
while($tmp_font = $sth->fetchrow_hashref) {
	%$font = %$tmp_font;
	$font->{'filetype'}	= $font->{'font_filetype'};
	$font->{'location'}	= $font->{'font_path'};
	$font->{'name'}		= $font->{'font_name'};
#	$image_name=$font->fontlinge_Imagename( $my_preview_path );
	$image_name=$font->fontlinge_Imagename( $my_preview_suffix );
	if (! -e $image_name) {
		print "Missing: $image_name\n";
	} else {
		$klein = new Image::Magick;
		$klein->Read($image_name);
		($w, $h) = $klein->Get('width', 'height');

		$image->Composite(	image		=>$klein,
					x		=>$x ,
					y		=>$y
		);

		$image->Annotate( 	text		=>$font->{'font_name'}, 
					x		=>$x ,
					y		=>$y+$h+$subline_distance ,
					fill		=>'black' ,
					undercolor	=>'white' ,
					font		=>$subline_font ,
					pointsize	=>$subline_fontsize ,
					antialias	=>1
		);

		undef $klein;
		$there_is_content=1;
		$y+=$h + $subline_distance + $y_gap;
		if ($y + $h + $subline_distance + $y_gap > $max_height) { # another one will not fit: New column
			&line_right;
			$y=0;
			$x+=$w + $x_gap + $x_rgap + $strokewidth;
			if ($x+$w + $x_gap + $x_rgap + $strokewidth > $max_width) { # another one will not fit: New spread
				&save_spread;
				&create_spread;
			}
		}
	}
}
&line_right;
&save_spread;

$sth->finish;
fontlinge_Close_Database($dbh);





sub create_spread {
	print "creating spread...";
	$spread_nr++;
	if( defined $image) {undef $image;}
	$image=Image::Magick->new(size=>"$max_width"."x"."$max_height");
	$image->ReadImage('xc:white');
	$image->Set(monochrome=>'True');
	$x=0;
	$y=0;
	print "done.\n";
	$there_is_content=0;
}

sub save_spread {
	if($there_is_content==1) {
		my $tmp=substr("0000".$spread_nr,-4);
		print "saving spread $tmp...";
		$wrn = $image->Write("montage_$tmp.png");
		warn "$wrn" if "$wrn";
		print "done.\n";
	}
}

sub line_right {
	if( $there_is_content==1 ) {
		$image->Draw(	fill		=>'white',
				primitive	=>'rectangle',
				antialias	=>0,
				strokewidth	=>0,
				stroke		=>'white',
				points		=>($x+$w-1+$x_rgap+$strokewidth).",0 $max_width,$max_height"
		);
	}
	if( ($there_is_content==1) && ($strokewidth>0) ) {
		$image->Draw(	fill		=>'black',
				primitive	=>'rectangle',
				antialias	=>0,
				points		=>($x+$w+$x_rgap).",0 ".($x+$w+$x_rgap+$strokewidth-1).",$max_height"
		);
	}
}

sub help {
	print "
Usage: 

fontlinge_montage --list-fonts
   --list-fonts          List known fonts in system(!) usable for
                         --subline-font

or

fontlinge_montage --list-categories
   --list-categories     List known font categories, use numbers in --query

or

fontlinge_montage [Options]
   --width=x             Width of poster
   --height=x            Height of poster
   --order='xxx'         Sort order in MySQL-query (hint: try 'font_name')
   --subline-distance=x  Distance between preview and subline
   --subline-fontsize=x  Fontsize of subline
   --subline-font='xxx'  Font used for subline (hint: try
                        'fontlinge_montage --list-fonts' and pick one)
   --y-gap=x             Vertical distance between previews
   --x-gap=x             horizontal distance between borderline and preview
                         (right side of line)
   --x-rgap=x            horizontal distance between borderline and preview
                         (left side of line)
   --strokewidth=x       Width of line
   --query='xxx'         MySQL-query which fonts are to be used.
                         Hint: try something like
                         \"font_name LIKE '%' AND font_kategorie=3\"
  --my-preview-suffix=x  Some identifier like large,color,... NOT gif,jpg,...
  --my-code=x            Include own perl-code. See manual.
";
}
#   --my-preview-path=x   Path to own perl-code to generate the path for previews

