#!/usr/bin/perl
use autodie;

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

my $indico_xml = 'abstracts.xml';
my $odt_file   = 'abstracts.odt';

my $xs = XML::Simple->new();
my $tree;
{
	open(my $fh, '<:raw', $indico_xml);
	local $/ = undef;
	my $xml = <$fh>;
#	warn dump($xml);
	$tree = $xs->XMLin( $xml, ForceArray => qw(PrimaryAuthor) );
}

my $abstracts = delete $tree->{abstract};

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

use	OpenOffice::OODoc	2.101;
my $doc = odfDocument(file => $odt_file, create => 'text');

my $stat;
my $id2nr;

$doc->createStyle(
	"Abstract",
	family		=> 'paragraph',
#	parent		=> 'Default Style',
#	category	=> 'auto',
	properties	=> {
		-area			=> 'paragraph',
		'fo:text-align'	=> 'justify'
	}
);


my $nr = 0;
foreach my $abstract ( @$abstracts ) {

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

	foreach $k (qw( ContributionType )) {
		$stat->{$k}->{ $abstract->{$k}->[0] } ++;
	}

	my $f = $abstract->{field};

	push @{ $stat->{_symposium}->{ $f->{1}->{'content'} } }, $id if exists $f->{1}->{content};
	push @{ $stat->{_theme}->{     $f->{2}->{'content'} } }, $id if exists $f->{2}->{content};

	$stat->{field}->{ $_ }++ foreach keys %$f;

	$id2nr->{ $id } = $nr++;

	my $t = $doc->appendParagraph(text => $abstract->{Title}->[0], style => 'Heading 1');
	$doc->setPageBreak( $t, position => 'before', style => 'Heading 1');

	foreach my $a ( @{ $abstract->{PrimaryAuthor} } ) {
		$doc->appendParagraph(text => join(' ',
			map { $a->{$_}->[0] } qw( FirstName FamilyName Email Affiliation )
		), style => 'Heading 2');
		push @{ $stat->{_Affiliation}->{ $a->{Affiliation}->[0] } }, $id;
	}

	$doc->appendParagraph(text => $abstract->{Content}->[0], style => 'Abstract');
	
	$doc->appendParagraph(text => "Theme: " . $f->{2}->{'content'}, style => 'Theme');

}

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

$doc->save;

