import xml 
import xml.etree.ElementTree as ET
from collections import defaultdict

PREFIX = defaultdict(lambda: "Svg.Attributes")
#PREFIX['href'] = 'Html.Attributes'


def open_file(filename):
	with open(filename) as f:
		return ET.fromstring(f.read())



def fix_tag(tag):
	if '}' not in tag:
		parts = tag.split('-')

		return parts[0] + ''.join(s.title() for s in parts[1:])

	(namespace, _, splitted_tag) = tag.partition('}')

	if splitted_tag == 'href':
		return 'xlinkHref'

	if not namespace.endswith('svg'):
		return None

	parts = splitted_tag.split('-')

	return parts[0] + ''.join(s.title() for s in parts[1:])

def node_to_elm(node, indent=0):

	base = "\nSvg." + fix_tag(node.tag)
	base += "\n  [ "
	base += '\n  , '.join('{prefix}.{k} "{v}"'.format(
			prefix=PREFIX[fix_tag(k)], 
			k=fix_tag(k), 
			v=v
		) 
		for (k, v) in node.attrib.items()
		if fix_tag(k)
	)
	base += "\n  ]"

	base += "\n  [ "
	base += '\n  , '.join([ node_to_elm(child, indent + 2) for child in node])
	base += "\n  ]"

	return '\n'.join(" " * indent + line for line in base.split('\n'))



def main():
	tree = open_file('example.svg')

	with open('output.elm', 'w') as f:
		f.write("""
import Html.Attributes exposing (href)
import Svg exposing (..)
import Svg.Attributes exposing (..)
        """)
		f.write("\nmain = " + node_to_elm(tree, indent=2))

if __name__ == '__main__':
	main()