#!/usr/bin/perl

use warnings;
use strict;
use autodie;

use Text::CSV qw( csv );
use Data::Dump qw( dump );
use JSON;
use Clone qw( clone );
use autodie;

use utf8;

my $file = 'keramika.csv';
my $aoh = csv (in => $file, headers => "auto");

open(my $fh, '>', 'keramika.js');
my $json;

foreach my $i ( @$aoh ) {
	my $source = sprintf( "../ZBIRKA-NEOLITIK/%d.png", $i->{ID} );
	my $image = sprintf( "image/%d.jpg" , $i->{ID} );
	my $thumb = sprintf( "thumb/%d.jpg" , $i->{ID} );

	if ( ! -e $source ) {
		warn "ERROR: no image $source";
		next;
	}

	system "convert -trim -geometry 400x $source $image";
	#system "convert $image -scale 100x100 -gravity center -background white -extent 100x100 $thumb";
	system qq{convert $source -fill white -draw "color 1,1 floodfill" -scale 100x100 -gravity center -background white -extent 100x100 $thumb};
	$i->{image} = $image;
	$i->{thumbnail} = $thumb;
#	$i->{label} = $i->{opis_predmeta};
	$i->{label} = $i->{ID};

	foreach my $name ( keys %$i ) {
		if ( length($i->{$name}) == 0 || $i->{$name} =~ m{^(nema|n/a)$} ) {
			delete $i->{$name};
		}
	}

	if ( defined($i->{ukras}) ) {
		my @ukrasi = split(/\s*,\s+|\s+i\s+/, $i->{ukras});
		$i->{ukrasi_array} = [ @ukrasi ];
	}

	if ( defined($i->{očuvan_dio_posude} ) ) {
		my @ocuvan = split(/\s*,\s+|\s+i\s+/, $i->{očuvan_dio_posude});
		$i->{ocuvan_array} = [ @ocuvan ];
	}

	warn "# i = ",dump($i);
	push @{ $json->{items} }, $i;
#	foreach my $n ( 1 .. 1000 ) {
#		my $i2 = clone $i;
#		$i2->{label} .= "_" . $n;
#		push @{ $json->{items} }, $i2;
#	}
}

print $fh encode_json( $json );
close($fh);

