#!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain a
# copy of the License at:
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# Cobbled together by Thorsten Behrens <thb@openoffice.org>
#
import sys, os, os.path
import xml.etree.ElementTree as ElemTree

placeholder_layer = "Size Placeholder Document Symbols"
inputFileName = sys.argv[1]

def exportRect(rects):
    if "{http://www.inkscape.org/namespaces/inkscape}label" in rects.attrib:
        attrib = rects.attrib["{http://www.inkscape.org/namespaces/inkscape}label"]
        if len(attrib) > 0 and attrib.split('_') > 1:
            parts = attrib.split('_')
            name = parts[0]
            size = parts[1]
            hc = len(parts) > 2 and parts[2].endswith("hc")
            print " found %s, size %s, hc is %d"%(name, size, hc)
            os.system("inkscape -i %s -e %s %s"%(rects.attrib["id"],name+size+("hc" if hc else "")+".png",inputFileName))
        

infile = open(inputFileName)
svg = ElemTree.XML(infile.read())
for groups in svg.findall(".//{http://www.w3.org/2000/svg}g"):
    if ("{http://www.inkscape.org/namespaces/inkscape}label" in groups.attrib
       and groups.attrib["{http://www.inkscape.org/namespaces/inkscape}label"] == placeholder_layer):
        for rects in groups.findall(".//{http://www.w3.org/2000/svg}rect"):
            exportRect(rects)
        for rects in groups.findall(".//{http://www.w3.org/2000/svg}use"):
            exportRect(rects)
