/***************************************************************************

    source::worx xtree
    Copyright © 2024-2025 c.holzheuer
    christoph.holzheuer@gmail.com

    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 <xqnodewriter.h>

#include <QFile>
#include <QXmlStreamWriter>

#include <xqnode.h>




//! schreibt einen (teil)baum in ein file

void XQNodeWriter::dumpTree( XQNodePtr rootNode, const QString& fileName ) const
{  
  QFile treeFile( fileName );
  if (!treeFile.open(QIODevice::WriteOnly | QIODevice::Text))
    throw XQException("can't open", fileName);

  QXmlStreamWriter writer(&treeFile);
  writer.setAutoFormatting(true); // Makes the output more readable
  writer.writeStartDocument();

  dumpNode( writer, rootNode );

  writer.writeEndDocument();
  treeFile.close();
}


//! schreibt einen knoten in einen stream

void XQNodeWriter::dumpNode( QXmlStreamWriter& writer, XQNodePtr node ) const
{
  //qDebug() << " --- dumpNode: id:" << node._id;

  writer.writeStartElement(node->tag_name() );

  if( !node->attributes().empty() )
  {
    for( const auto& attrEntry : node->attributes() )
      writer.writeAttribute( attrEntry.first , attrEntry.second );
  }

  if( node->has_children() )
  {
    for (auto& child : node->children())
      dumpNode( writer, child );
  }

  writer.writeEndElement();
}
