#!/usr/bin/perl
use autodie;
use warnings;
use strict;

use utf8;
use XML::Simple;
use Data::Dump qw(dump);

my $xs = XML::Simple->new();

my $stat;
my $abstracts;

my $xml;
open(my $fh, '<:encoding(utf-8)', 'contributions/all.xml');
{
	local $/ = undef;
	$xml = <$fh>;
	close($fh);
}

#warn "---xml---", dump($xml), "---/xml---\n";

foreach my $xml ( split(/\Q<?xml\E/, $xml) ) {

	next unless $xml;

	$xml = '<?xml' . $xml;

	my $abstract;

	$abstract = $xs->XMLin( $xml, ForceArray => qw(PrimaryAuthor) );

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

	my $id = $abstract->{'Id'}->[0] || die "no Id in ",dump($abstract);
	warn "# $id abstract = ", dump($abstract);

	foreach my $k (qw( ContributionType )) {
		push @{ $stat->{$k}->{ $abstract->{$k}->[0] } }, $id;
	}

	if ( $abstract->{'ContributionType'}->[0] eq 'Symposium proposal' ) {
		my $t = $abstract->{Title}->[0];
		push @{ $stat->{_symposium}->{ $t } }, -$id;
	}

	if ( my $s = $abstract->{Symposium_title} ) {
		$s = $s->[0];
		push @{ $stat->{_symposium}->{$s} }, $id;
	}

	if ( exists $abstract->{PrimaryAuthor}->[0]->{FamilyName} ) {
		$stat->{_order_by}->{$id} = $abstract->{PrimaryAuthor}->[0]->{FamilyName}->[0];
	}

	$abstracts->{ $id } = $abstract;

}

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

use Text::CSV;

my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
	or die "Cannot use CSV: ".Text::CSV->error_diag ();

my @program;
 
open my $fh, "<:encoding(utf8)", "session-code.csv" or die "csv: $!";
while ( my $row = $csv->getline( $fh ) ) {
	warn dump($row);
	push @program, $row;
}
$csv->eof or $csv->error_diag();
close $fh;

open(my $program_fh, '>', 'program.html');
print $program_fh qq{<table>\n};

foreach my $p ( sort { $a->[6] cmp $b->[6] || $a->[1] cmp $b->[1] } @program ) {
	my $abstract = $abstracts->{ $p->[0] } || die "no abstract for ", $p->[0];
	my $authors;
	foreach my $a ( @{ $abstract->{PrimaryAuthor} } ) {
		$authors .= '; ' . $a->{FamilyName}->[0] . ', ' . $a->{FirstName}->[0];
	}
	$authors =~ s/^; //;
	print $program_fh "<tr><td>", join("</td><td>", $p->[1], $p->[6], $p->[0], $p->[4] . '<br>' . $authors), "</td></tr>\n";
}

close $program_fh;

