#!/usr/bin/env python
# -*- coding: utf-8 -*-
# we saw thislike file structure
__author__ = "Volker Heggemann, Melle, DE"
__copyright__ = "Copyright (C) 2020 Volker Heggemann"
__license__ = "CC BY 3.0 DE"
__version__ = "1.0"

import os
from xml.sax.saxutils import quoteattr as xml_quoteattr

def make_xmlfile(path):

    #recursive function
    def DirAsLessXML(path):
        result = '<category name=%s>\n' % xml_quoteattr(os.path.basename(path))
        prefix = ''
        for item in os.listdir(path):
            itempath = os.path.join(path, item)
            if os.path.isdir(itempath):
                result += '\n'.join('   ' + line for line in
                                    DirAsLessXML(os.path.join(path, item)).split('\n'))
                result += '   \n'
            elif os.path.isfile(itempath):
                if item == 'tagfile.txt':
                    x = open(itempath, 'r')
                    prefix = x.read(1)
            #     pass
            #     #result += '  <file name=%s />\n' % xml_quoteattr(item)

        result += '   <prefix>' + prefix + '</prefix>\n'
        result += '</category>\n'
        return result

    xmltxtfile = '<?xml version="1.0" encoding="utf-8"?>\n<labels>\n' + DirAsLessXML(path) + '\n</labels>'
    return xmltxtfile


def main(inpath='', outfile='demo.xml', show=True):
    """ Main program """
    if inpath == '':
        inpath = os.path.expanduser('~')
    lookpath = inpath + '/.qet/elements/'
    outstr = make_xmlfile(lookpath)

    f = open(inpath + os.path.sep + outfile, "w+")
    f.write(outstr)
    if show:
        print(outstr)

if __name__ == '__main__':
    import plac
    plac.call(main)
