/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
#include "cmXMLWriter.h"

#include <cassert>

#include "cmsys/FStream.hxx"

cmXMLWriter::cmXMLWriter(std::ostream& output, std::size_t level)
  : Output(output)
  , IndentationElement(1, '\t')
  , Level(level)
  , Indent(0)
  , ElementOpen(false)
  , BreakAttrib(false)
  , IsContent(false)
{
}

cmXMLWriter::~cmXMLWriter()
{
  assert(Indent == 0);
}

void cmXMLWriter::StartDocument(const char* encoding)
{
  Output << R"(<?xml version="1.0" encoding=")" << encoding << "\"?>";
}

void cmXMLWriter::EndDocument()
{
  assert(Indent == 0);
  Output << '\n';
}

void cmXMLWriter::StartElement(std::string const& name)
{
  CloseStartElement();
  ConditionalLineBreak(!IsContent);
  Output << '<' << name;
  Elements.push(name);
  ++Indent;
  ElementOpen = true;
  BreakAttrib = false;
}

void cmXMLWriter::EndElement()
{
  assert(Indent > 0);
  --Indent;
  if (ElementOpen) {
    Output << "/>";
  } else {
    ConditionalLineBreak(!IsContent);
    IsContent = false;
    Output << "</" << Elements.top() << '>';
  }
  Elements.pop();
  ElementOpen = false;
}

void cmXMLWriter::Element(const char* name)
{
  CloseStartElement();
  ConditionalLineBreak(!IsContent);
  Output << '<' << name << "/>";
}

void cmXMLWriter::BreakAttributes()
{
  BreakAttrib = true;
}

void cmXMLWriter::Comment(const char* comment)
{
  CloseStartElement();
  ConditionalLineBreak(!IsContent);
  Output << "<!-- " << comment << " -->";
}

void cmXMLWriter::CData(std::string const& data)
{
  PreContent();
  Output << "<![CDATA[" << data << "]]>";
}

void cmXMLWriter::Doctype(const char* doctype)
{
  CloseStartElement();
  ConditionalLineBreak(!IsContent);
  Output << "<!DOCTYPE " << doctype << ">";
}

void cmXMLWriter::ProcessingInstruction(const char* target, const char* data)
{
  CloseStartElement();
  ConditionalLineBreak(!IsContent);
  Output << "<?" << target << ' ' << data << "?>";
}

void cmXMLWriter::FragmentFile(const char* fname)
{
  CloseStartElement();
  cmsys::ifstream fin(fname, std::ios::in | std::ios::binary);
  Output << fin.rdbuf();
}

void cmXMLWriter::SetIndentationElement(std::string const& element)
{
  IndentationElement = element;
}

void cmXMLWriter::ConditionalLineBreak(bool condition)
{
  if (condition) {
    Output << '\n';
    for (std::size_t i = 0; i < Indent + Level; ++i) {
      Output << IndentationElement;
    }
  }
}

void cmXMLWriter::PreAttribute()
{
  assert(ElementOpen);
  ConditionalLineBreak(BreakAttrib);
  if (!BreakAttrib) {
    Output << ' ';
  }
}

void cmXMLWriter::PreContent()
{
  CloseStartElement();
  IsContent = true;
}

void cmXMLWriter::CloseStartElement()
{
  if (ElementOpen) {
    ConditionalLineBreak(BreakAttrib);
    Output << '>';
    ElementOpen = false;
  }
}
