#!/usr/bin/perl -w
# Copyright 2005 Jean-Michel Fayard jmfayard_at_gmail.com
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public
#   License as published by the Free Software Foundation; either
#   version 2 of the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; see the file COPYING.  If not, write to
#   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#   Boston, MA 02111-1307, USA.


use strict;
use Image::Kimdaba;
use English qw( -no_match_vars ) ;

print "Checking if you have convert from ImageMagick package\n";
my $res=system("which convert");
die "You need to install Image::Magick module and ImageMagieck" unless $res==0;

my $folder=getRootFolder();
print "Parsing the ${folder}/index.xml database...\n";
parseDB( "$folder" );

my %founds=();
my %founds_alone=();

URL:	while( my( $url, $r_hash) = each %imageoptions)
#for my $url (sort keys %imageoptions)
{
    next unless (-e "${folder}/${url}" );
#my %options=%{ $imageoptions{$url} };
    my %options=%$r_hash;
OPTION:    while( my( $option, $r_values) = each %options )
    {
VALUE:	for my $value (@$r_values)
	{
	    my $key ="$option-$value";
	    next VALUE if( exists $founds_alone{$key} );
	    my @values=@$r_values;
	    if (scalar @values==1)
	    {
		$founds_alone{$key}=$url;
	    } else {
		next VALUE if(exists $founds{$key});
		$founds{$key}=$url;
	    }
	}
    }
}

print "==only that value==\n";
while( my( $key,$url) = each %founds_alone)
{
    delete $founds{$key};
    $key=~s/ /_/g;
    next if(-e "${folder}/CategoryImages/${key}.jpg");
    print "Categoryimage for $key :  $url\n";
    $key=~s/'/'\\''/g;
    $url=~s/'/'\\''/g;
system("convert -size 128x128 '$folder/$url' -resize 128x128  '$folder/CategoryImages/${key}.jpg'");
}


print "\n\n";
print "==that value and others==\n";
while( my( $key,$url) = each %founds)
{
    $key=~s/ /_/g;
    next if(-e "${folder}/CategoryImages/${key}.jpg");
    print "Categoryimage for $key :  $url\n";
    $key=~s/'/'\\''/g;
    $url=~s/'/'\\''/g;
system("convert -size 128x128 '$folder/$url' -resize 128x128  '$folder/CategoryImages/${key}.jpg'");
}
print "\n\n";
