#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
use Text::Restructured;
use YAML;

my $input=<<'EOF';
======
 Test
======
:Author: dakkar

paragrafo

link

mathml: :mathml:`x^2`

.. mathml::

  (x^2)/(y^2)

pre::

  gino  pino
 rino

normale

:titlink:`/path/al/doc/`

EOF
my $name='--inline--';

my $opts={
    D => {
        generator => 0,
        'source-link' => 0,
        'time' => 0,
    },
};
my $parser=Text::Restructured->new($opts,'gino');
if (@ARGV) {
    $name=$ARGV[0];
    $input=do{open my $fh,'<',$name;local $/;<$fh>};
}

# bad MNODINE, no cookie
# MY_ROLES gets re-inited before every Parse, so I have to change a
# global variable
$Text::Restructured::ROLES{titlink}={
    tag => 'reference',
    attr => {
        refuri => '%s',
        role => sub {
            my ($parser,$attr,$text,$role)=@_;
            $role;
        }
    },
    text => 'dummy',
};

my $dudom=$parser->Parse($input,$name);

my $xdoc=XML::LibXML->createDocument();

my $MATHML='http://www.w3.org/1998/Math/MathML';
sub mathml2xml {
    my ($mnode)=@_;

    if ($mnode->isText) {
        return $xdoc->createTextNode($mnode->nodeValue);
    }


    my @children=map {mathml2xml($_)}
        $mnode->childNodes();

    my $elem=$xdoc->createElementNS($MATHML,$mnode->nodeName);
    for my $attname ($mnode->attributeList) {
        next if $attname eq 'xmlns';
        $elem->setAttribute($attname,
                            $mnode->attribute($attname))
    }

    $elem->appendChild($_) for @children;

    return $elem;
}

sub docutils2xml {
    my ($dunode)=@_;

    if ($dunode->{tag} eq '#PCDATA') {
        return $xdoc->createTextNode($dunode->{text} || '');
    }

    if ($dunode->{tag} eq 'mathml') {
        return mathml2xml($dunode->{attr}{mathml});
    }

    my @children=map {docutils2xml($_)}
        @{ $dunode->{content} || [] };

    my $elem=$xdoc->createElement($dunode->{tag});

    if (defined $dunode->{attr}) {
        while (my ($attname,$attval)=each %{$dunode->{attr}}) {
            if (! defined $attval) {
                $attval='';
            }
            elsif (ref($attval) eq 'ARRAY') {
                $attval=join ' ',@$attval;
            }
            $elem->setAttribute($attname,$attval);
        }
    }
    $elem->appendChild($_) for @children;

    return $elem;
}
$xdoc->setDocumentElement(docutils2xml($dudom));
print $xdoc->toString();
