#! /usr/bin/env python

import os
from optparse import OptionParser
import subprocess
import tempfile
import xml.etree.ElementTree as ET
import re
from PIL import Image
from PIL import PngImagePlugin
import sys

parser = OptionParser()
parser.add_option('-c', '--colour', dest='colour', metavar='COLOUR')
parser.add_option('-v', '--variant', dest='variant', metavar='VARIANT')
parser.add_option('-w', '--width', dest='width', metavar='WIDTH', default='42')
(options, args) = parser.parse_args()

for svg_path in args:
    output_filename = svg_path.replace('.svg', '.png')
    svg_path = os.path.join('sources', svg_path)
    if options.variant:
        output_filename = output_filename.replace('.png', '-%s.png' % options.variant)
    author = None
    if options.colour:
        tree = ET.fromstring(file(svg_path).read().replace('#000000', '#%s' % options.colour))
        for elem in tree.findall('*'):
            if not elem.attrib.get('style'):
                elem.attrib['style'] = 'fill:#%s' % options.colour
        for elem in tree.getchildren():
            if elem.tag == '{http://www.w3.org/2000/svg}text' and elem.text.startswith('Created by'):
                author = elem.text[len('Created by')+1:]
                tree.remove(elem)
        for elem in tree.getchildren():
            if elem.tag == '{http://www.w3.org/2000/svg}text' and 'Noun Project' in elem.text:
                tree.remove(elem)
        f = tempfile.NamedTemporaryFile(suffix='.svg', delete=False)
        f.write(ET.tostring(tree))
        f.close()
        svg_path = f.name
    # XXX: add author to png metadata
    subprocess.call(['inkscape', '--without-gui',
        '--file', svg_path,
        '--export-area-drawing',
        '--export-area-snap',
        '--export-png', output_filename,
        '--export-width', options.width])
