#!/usr/bin/env python

from __future__ import print_function

import emitter

class XMLEmitter(emitter.Emitter):
    def preface(self):
        return """<?xml version="1.0" encoding="utf-8"?>
<!-- Dynamically generated list of documented logfile messages (generated by parse.py) -->
<loggermessagefile>
"""
    def postface(self):
        return "</loggermessagefile>"

    def start(self):
        self.fh = open("LogMessages.xml", mode='w')
        print(self.preface(), file=self.fh)

    def emit(self, doccos):
        self.start()
        for docco in doccos:
            print('    <logformat name="%s">' % docco.name, file=self.fh)
            if docco.url is not None:
                print('        <url>%s</url>' % docco.url, file=self.fh)
            if docco.description is not None:
                print('        <description>%s</description>' %
                      docco.description, file=self.fh)
            print('        <fields>', file=self.fh)
            for f in docco.fields_order:
                print('            <field name="%s">' % f, file=self.fh)
                if "description" in docco.fields[f]:
                    print('                <description>%s</description>' %
                          docco.fields[f]["description"], file=self.fh)
                if "bits" in docco.fields[f]:
                    print('                <bits>%s</bits>' %
                          docco.fields[f]["bits"], file=self.fh)
                print('            </field>', file=self.fh)

            print('        </fields>', file=self.fh)

            print('    </logformat>', file=self.fh)

            print("", file=self.fh)
        self.stop()

    def stop(self):
        print(self.postface(), file=self.fh)
        self.fh.close()
