#!/usr/bin/env python3

"""usage:
    enyx-hw-codegen-board-dump [list of xml]

Two output files will be created for each xml file.
"""

import argparse
import os
import sys
from lxml import etree
from jinja2 import Environment, FileSystemLoader
from enyx_hw_gen import core_from_xml


def remove_xml_namespace(root: etree.Element):
    for elem in root.getiterator():
        elem.tag = etree.QName(elem).localname
    etree.cleanup_namespaces(root)

def main():
    parser = argparse.ArgumentParser(description='Generate code from template')
    parser.add_argument('--output', '-o', help='output directory',
                        default='output')
    parser.add_argument('--xml-descriptions', '-x', required=True,
                        help='XML cores descriptions to translate', nargs='+')
    parser.add_argument('--template-folder', '-f',
                        help='path to template folder')
    parser.add_argument('--templates', '-t', required=True,
                        help='Templates to use', nargs='+')

    args = parser.parse_args()

    env = Environment(loader=FileSystemLoader(args.template_folder))

    for description in args.xml_descriptions:
        with open(description) as f:
            xml_parser = etree.XMLParser(remove_comments=True)
            doc = etree.parse(f, xml_parser)
        root = doc.getroot()
        remove_xml_namespace(root)

        if root.tag != "Board":
            print("'{}' does not look like an inspector dump, skipping"
                  .format(description), file=sys.stderr)
            continue

        cores = list(map(core_from_xml, root))
        bus_addr_width = int(root.attrib['bus_addr_width'])
        
        for template_name in args.templates:
            template = env.get_template(template_name)
            input_file_name = os.path.basename(description)
            
            mod = template.make_module({'cores': cores, 'input_file_name': input_file_name})
            output_file_path = mod.output_file_path()
            
            os.makedirs(os.path.dirname(os.path.join(args.output,
                                                     output_file_path)),
                        exist_ok=True)
            with open(os.path.join(args.output, output_file_path),
                      'w') as f:
                f.write(template.render(cores=cores, input_file_name=input_file_name, bus_addr_width=bus_addr_width))

            print("'{}' generated from '{}' XML dump".format(output_file_path,
                                                             description))


if __name__ == '__main__':
    main()
