#!/usr/bin/env python
from __future__ import print_function, unicode_literals

from lxml import etree
import os


def main(var_name, files):
    svgdata = []
    for svgfile in files:
        with open(svgfile, 'r') as f:
            parser = etree.XMLParser(ns_clean=True)
            tree = etree.parse(f, parser=parser)
            root = tree.getroot()
            default_ns = root.nsmap.get(None, '')

            def fqname(name):
                if default_ns:
                    return '{%s}%s' % (default_ns, name)
                return name

            if root.tag != fqname('svg'):
                print ('Unknown root element %s' % root.tag)
                return 1
            data = {
                'iconname': os.path.splitext(os.path.basename(svgfile))[0],
                'view_box': root.get('viewBox', ''),
                'width': root.get('width'),
                'height': root.get('height'),
                'path': '',
                'fill': 'null',
            }

            children = list(root)
            for child in children:
                if child.tag == fqname('path'):
                    data['path'] = child.get('d', '')
                    data['fill'] = child.get('fill', '""')
                    break

            svgdata.append("""
    %(iconname)s: (
        view_box: %(view_box)s,
        width: %(width)s,
        height: %(height)s,
        path: "%(path)s",
        fill: %(fill)s
    )""" % data)

    print ('// Auto generated by iconsvg2scss.py.')
    print ('$%s: (' % var_name)
    print (',\n'.join(svgdata))
    print (');')
    return 0

if __name__ == '__main__':
    import sys
    argv = sys.argv
    if len(argv) < 3:
        print ('Usage: %s <var_name> <file1.svg>...' % argv[0])
        sys.exit(1)
    sys.exit(main(argv[1], argv[2:]))
