/***************************************************************************
 *   Copyright (C) 2005-2006 Nicolas Hadacek <hadacek@kde.org>             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/
#include "xml_to_data.h"

#include <tqfile.h>
#include <tqtextstream.h>

TQDomElement XmlToData::findUniqueElement(TQDomElement parent, const TQString &tag,
                                         const TQString &attribute, const TQString &value) const
{
  TQDomElement element;
  TQDomNode child = parent.firstChild();
  while ( !child.isNull() ) {
    if ( child.nodeName()==tag && child.isElement()
         && (attribute.isEmpty() || child.toElement().attribute(attribute)==value) ) {
      if ( !element.isNull() ) tqFatal(TQString("Duplicated element \"%1/%2\"").arg(tag).arg(value));
      element = child.toElement();
    }
    child = child.nextSibling();
  }
  return element;
}

void XmlToData::checkTagNames(TQDomElement element, const TQString &tag,
                              const TQStringList &names) const
{
  TQDomNodeList list = element.elementsByTagName(tag);
  for (uint i=0; i<uint(list.count()); i++) {
    if ( !list.item(i).isElement() ) continue;
    TQString name = list.item(i).toElement().attribute("name");
    if ( names.find(name)==names.end() ) tqFatal(TQString("Illegal name %1 for %2 element").arg(name).arg(tag));
  }
}

TQDomDocument XmlToData::parseFile(const TQString &filename) const
{
  tqDebug("Parsing XML file \"%s\"...", filename.latin1());
  TQFile file(filename);
  if ( !file.open(IO_ReadOnly) ) tqFatal("Cannot open file!");
  TQDomDocument doc;
  TQString error;
  int errorLine, errorColumn;
  if ( !doc.setContent(&file, false, &error, &errorLine, &errorColumn) )
    tqFatal(TQString("Error parsing XML file (%1 at line %2, column %3)").arg(error).arg(errorLine).arg(errorColumn));
  return doc;
}

void XmlToData::warning(const TQString &message) const
{
  if ( currentDevice().isEmpty() ) ::tqWarning("Warning: %s", message.latin1());
  else ::tqWarning("Warning [%s]: %s", currentDevice().latin1(), message.latin1());
}
void XmlToData::tqFatal(const TQString &message) const
{
  if ( currentDevice().isEmpty() ) ::tqFatal("Fatal: %s", message.latin1());
  else ::tqFatal("Fatal [%s]: %s", currentDevice().latin1(), message.latin1());
}

void XmlToData::process()
{
  parse();
  tqDebug("Parsing XML successful.");
  output();
  tqDebug("Output written.");
}
