// Dom2.java
//
// Modifie un arbre DOM

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import java.io.File;
import java.io.IOException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.DOMException;

public class Dom2
{
  public static void main (String argv [])
            throws IOException
    {
     if (argv.length != 1) {
        System.err.println ("Usage: cmd filename");
        System.exit (1);
    }
    DocumentBuilderFactory factory =
                          DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.parse( new File(argv[0]) );
      Element  rootElement =  document.getDocumentElement () ;
      modifieDomTree (rootElement);
      printDomTree (document, "");
    } catch (Throwable t) {
      t.printStackTrace ();
      System.exit (1);
    }
    System.exit (0);
  }

  public static void modifieDomTree (Node node)
    {
       Node repliqueNode = getNextNode(node, "replique");
       while (repliqueNode != null) {
           Node personneNode = getNextNode (repliqueNode, "personnage");
           Node texteNode = getNextNode (repliqueNode, "texte");
           if ((personneNode != null) && (texteNode != null))
             repliqueNode.insertBefore(texteNode, personneNode);
           repliqueNode = repliqueNode.getNextSibling();
       }
     }

  public static Node getNextNode (Node node, String name )
    {
      if (node.getNodeName().equals(name))
           return node;
      if (node.hasChildNodes())  {
         Node goodNode = null;
         NodeList list = node.getChildNodes();
         for (int i = 0; i < list.getLength(); i ++)  {
            goodNode = getNextNode (list.item(i), name) ;
            if (goodNode != null)
              return goodNode;
         }
         return null;
      }  else
         return null;
    }

  public static void printDomTree (Node node, String indent)
    { System.out.println(indent+"noeud name  : "+node.getNodeName());
      System.out.println(indent+"value : "+node.getNodeValue());
      if (node.hasChildNodes())  {
        Node nextFils = node.getFirstChild();
       while (nextFils != null) {
           printDomTree (nextFils,  indent+" ");
           nextFils = nextFils.getNextSibling();
       }
     }
   }
 }
