package net.sourceforge.phpeclipse.wizards.xml;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import com.quantum.util.StringMatrix;

public class ModelUtil {

  public static String getTableName(Element root) {
    NodeList columns = root.getElementsByTagName("table");
    for (int i = 0; i < columns.getLength(); i++) {
      Node column = columns.item(i);
      String header = column.getNodeName();
      if (header.equals("table")) {
        NamedNodeMap map = column.getAttributes();
        Node name = map.getNamedItem("name");
        if (name == null) {
          return "";
        }
        return name.getNodeValue();
      }
    }
    return "";
  }

  
  public static void xmlToStringMatrix(StringMatrix matrix, Element root, String sub) {
    NodeList columns = root.getElementsByTagName(sub);
    for (int i = 0; i < columns.getLength(); i++) {
      Node column = columns.item(i);
      NodeList columnList = column.getChildNodes();
      for (int j = 0; j < columnList.getLength(); j++) {
        Node node = columnList.item(j);
        String header = node.getNodeName();
        if (header.equals("#text")) //$NON-NLS-1$
          continue;
        String value = null;
        if (node != null && node.hasChildNodes()) {
          Node valueNode = node.getFirstChild();
          if (valueNode instanceof Text) {
            value = valueNode.getNodeValue();
          }
        }
        if (!matrix.contains(header))
          matrix.addHeader(header);
        matrix.addAt(header, value, i);
      }
    }
  }
}