#! /usr/bin/perl

use XML::Invoice::Parser;

# TODO: Iso8859 conversion should be optional

my($t)="/tmp/xrechnung.".int(10000*rand());
mkdir($t) || die "make tempdir $t failed";
my($f)=shift();
# system("cp $f $t") || die "cp $f $t failed"; # why does that not work?!
system("cp $f $t") ==0 or die "cp $f $t failed";
my($d)=".";
if ($f=~/(.*)\/(.*)/) { $d=$1; $f=$2 }
chdir($t) || die "cd $t failed";
system("pdfdetach -saveall $f") ==0 or die "pdfdetach -saveall $f failed";

open(_,'xrechnung.xml') || die "could not open xrechnung.xml"; 
my(@file)=<_>;
close(_) || die "could not close xrechnung.xml";
chomp(@file);
my($xml_data)=join('',@file);
if ($xml_data=~/[äöüÄÖÜß]/) {
  warn 'Iso8859 detected - this will cause major problems, trying to convert';
  $xml_data=~s/[äöüÄÖÜ]/$&e/g;
  $xml_data=~tr/äöüÄÖÜ/aouAOU/;
  $xml_data=~s/ß/ss/;
}
my $invoice_parser = XML::Invoice::Parser->new($xml_data);
my %metadata = %{$invoice_parser->metadata};
my @items = @{$invoice_parser->items};

for my $i (@items) {
  for (sort keys(%$i)) {
    print "$_: ".$$i{$_}."\n";
  }
}
