#! /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

mapping = {
    '207': 'trash',
    '1673': 'businessperson',
    '4335': 'sanitation',
    '6412': 'mobile-alarm',
    '8686': 'misc',
    '10860': 'triathlon',
    '12513': 'email',
    '12246': 'park',
    '13644': 'culture',
    '14004': 'document',
    '14292': 'polling-place',
    '23557': 'crosswalk',
    '32231': 'document',
    '38588': 'shopping-cart',
    '39826': 'people',
    '39567': 'tools',
    '40124': 'consultation',
    '49638': 'event',
    '58303': 'placeholder',
    '62444': 'fireworks',
    '64055': 'association',
    '79187': 'venue',
    '64233': 'convention-center',
    '22637': 'tourist',
    '168700': 'payment',
}

parser = OptionParser()
parser.add_option('-c', '--colour', dest='colour', metavar='COLOUR')
(options, args) = parser.parse_args()

for icon_id, icon_name in mapping.items():
    svg_path = 'src/icon_%s/' % icon_id
    svg_path = os.path.join(svg_path, [x for x in os.listdir(svg_path) if x.endswith('.svg')][0])
    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
    else:
        tree = ET.fromstring(file(svg_path).read())

    author = None
    for elem in tree:
        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:
        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

    if options.colour:
        output_filename = 'icon_%s_%s_%s.png' % (icon_name, icon_id, options.colour)
    else:
        output_filename = 'icon_%s_%s.png' % (icon_name, icon_id)

    subprocess.call(['inkscape', '--without-gui',
        '--file', svg_path,
        '--export-png', output_filename,
        '--export-area-drawing',
        '--export-area-snap',
        '--export-width', '42'])

    # write down licensing info in the png file
    meta = PngImagePlugin.PngInfo()
    if os.path.exists('src/icon_%s/license.txt' % icon_id):
        license_txt = open('src/icon_%s/license.txt' % icon_id).read()
        try:
            meta.add_text('Author', re.findall('by(.*)', license_txt)[0], 0)
        except IndexError:
            pass
        license_txt = license_txt.replace('\n', ' ')
        for license in ['Public Domain', 'Creative Commons Attribution']:
            if license in license_txt:
                meta.add_text('Licence', license, 0)
                break
        else:
            print >> sys.stderr, 'Warning: no license known for', svg_path
    else:
        # new noun project icon format, they do not specify a license, assume
        # Creative Commons Attribution
        license = 'Creative Commons Attribution'
        meta.add_text('Licence', license, 0)
        if author:
            try:
                meta.add_text('Author', author)
            except IndexError:
                pass

    png_file = Image.open(output_filename)
    png_file.save(output_filename, "PNG", pnginfo=meta)
