#!/usr/bin/perl

use LWP::Simple;
use JSON;
use Text::CSV;
use Data::Dump qw(dump);

my $csv = Text::CSV->new ({ binary => 1, auto_diag => 1 });
open(my $csv_fh, '>:encoding(utf8)', 'crossbi-export.csv') or die "crossbi-export.csv: $!";

my @columns;

while(<>) {
	chomp;
	my $radid = $_;

	my $result = get("https://www.bib.irb.hr/$radid/json");
	warn "# result = $result\n";

	my $json   = decode_json $result;

	warn "# json = ",dump($json);

	if ( ! @columns ) {
		@columns = sort grep { !/urls/ } keys %{$json->{items}->[0]};
		warn "## columns = ",dump(@columns);
		$csv->say( $csv_fh, \@columns );
	}

	my $row;
	foreach my $item ( @{ $json->{items} } ) {
		warn "## item = ",dump( $item );
		foreach my $col ( @columns ) {
			push @$row, $item->{$col};
		}
	}

	warn "# row = ",dump( $row );

	$csv->say( $csv_fh, $row );

}

close($csv_fh) or die "crossbi-export.csv: $!";

