#! /usr/bin/env python3

# publik-base-theme
# Copyright (C) 2016  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import os
import re
import subprocess
import sys
import xml.etree.ElementTree as ET

inkscape = os.path.abspath(os.path.join(os.path.dirname(__file__), 'inkscape_wrapper.py'))

names = {
    '02': 'famille',
    '03': 'papiers',
    '04': 'sante',
    '05': 'travail',
    '06': 'logement',
    '07': 'transport',
    '08': 'sport',
    '09': 'securite',
    '10': 'signalements',
    '11': 'dechets',
}

filenames = [
    'EO_CONNECTVILLE_PUBLIK_PICTO_02.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_03.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_04.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_05.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_06.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_07.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_08.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_09.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_10.svg',
    'EO_CONNECTVILLE_PUBLIK_PICTO_11.svg',
]

whitelist = [
    'M38.354,88.859l-3.',  # papiers/shirt
    'M96.213,42.521c-0.',  # signalements/1st wave
    'M101.516,45.251c-0',  # signalements/2nd wave
    'M111.558,47.581c-0',  # signalements/3rd wave
    'M118.346,102.92c-0',  # transport/cadre velo
    'M92.644,102.92c-0.',  # "
    'M92.643,102.92H70',  # "
    'M63.625,95.128c-7.',  # sante/wheelchair
    'M69.187,64.57c-0.3',  # sante/kid
    'M66.882,52.466c-0.',  # "
    'M90.321,95.128c-0.',  # "
    'M94.035,85.527c-0.',  # "
    'M68.871,60.921c-4.',  # "
    'M71.663,53.41c-0.2',  # "
    'M73.875,52.752c-0.',  # "
    'M114.493,43.283c-0',  # sante/stetho
    'M137.485,76.615c-0',  # "
    'M141.604,77.302c0,',  # "
    'M108.574,71.064L',  # logement/house
    'M96.33,80.938H84.',  # travail/briefcase outline
]
blacklist = [
    'M104.125,87.167H',  # famille/border
    'M83.83,46.362l0.4',  # papiers/i
    'M85.544,35.605l-0',  # papiers/d
    'M96.618,36.592l-0',  # papiers/e
    'M105.127,26.812l1',  # papiers/n
    'M111.078,28.917l0',  # papiers/t
    'M119.033,40.591l0',  # papiers/i
    'M123.222,26.927l0',  # papiers/t
    'M131.074,39.075l0',  # papiers/e
    'M92.208,95.872H59',  # travail/briefcase parts
    'M81.853,95.268c0,',  # "
]

parser = argparse.ArgumentParser()
parser.add_argument('path', help='out path')
parser.add_argument('--primary', default='E0037A')
parser.add_argument('--secondary', default='6D1F80')

args = parser.parse_args()
path_out = args.path

if not os.path.exists(path_out):
    os.makedirs(path_out)

for filename in filenames:
    outname = names.get(re.search(r'\d+', filename).group())

    fd = open('tmp-%s.svg' % outname, 'w')
    fd.write(
        open(os.path.join('pictos', filename))
        .read()
        .replace('E0037A', args.primary)
        .replace('6D1F80', args.secondary)
    )
    fd.close()
    subprocess.call(
        [
            inkscape,
            '--without-gui',
            '--file',
            'tmp-%s.svg' % outname,
            '--export-area-page',
            '--export-png',
            os.path.join(path_out, '%s.png' % outname),
            '--export-width',
            '128',
        ]
    )

    tree = ET.parse(open(os.path.join('pictos', filename)))
    parent_map = {c: p for p in tree.iter() for c in p}
    for i in range(10):
        for node in tree.iter():
            tag_name = node.tag.split('}')[-1]
            if tag_name == 'svg':
                continue
            if tag_name == 'g':  # keep groups
                continue
            if tag_name in ('linearGradient', 'polygon', 'rect', 'clipPath', 'polyline', 'circle'):
                if tag_name == 'circle' and outname == 'transport':
                    continue
                if tag_name == 'rect' and node.attrib.get('fill') == '#FFFFFF' and outname == 'travail':
                    continue
                parent_map[node].remove(node)
                continue
            if tag_name == 'path':
                in_whitelist = False
                for start in whitelist:
                    if node.attrib['d'].startswith(start):
                        in_whitelist = True
                        break
                if in_whitelist:
                    continue

                in_blacklist = False
                for start in blacklist:
                    if node.attrib['d'].startswith(start):
                        parent_map[node].remove(node)
                        in_blacklist = True
                        break
                if in_blacklist:
                    continue

                if not 'fill' in node.attrib and not 'fill' in node.attrib.get('style', ''):
                    parent_map[node].remove(node)
                    continue

                if node.attrib.get('fill') == '#6D1F80' or node.attrib.get('style') == 'fill:#6d1f80':
                    pass
                elif node.attrib.get('fill') == '#FFFFFF' and outname in ('signalements', 'sport', 'travail'):
                    pass
                else:
                    parent_map[node].remove(node)

    for node in tree.iter():
        tag_name = node.tag.split('}')[-1]
        if tag_name == 'g':
            if 'clip-path' in node.attrib:
                del node.attrib['clip-path']
        if 'style' in node.attrib:
            del node.attrib['style']
        if tag_name == 'path':
            if node.attrib.get('fill') == '#FFFFFF' or (
                node.attrib['d'].startswith('M120.281,98.383c-1')
                or node.attrib['d'].startswith('M108.574,71.064L')  # travail/skirt
                or node.attrib['d'].startswith('M37.523,66.207c0,5')  # logement/house
                or node.attrib['d'].startswith('M-9.2,66.207c0,5.2')  # transport/wheel
                or node.attrib['d'].startswith(  # transport/other wheel
                    'M96.33,80.938H84.'
                )  # travail/briefcase outline
            ):
                node.attrib['fill'] = 'none'
                node.attrib['stroke'] = '#FFFFFF'
            else:
                node.attrib['fill'] = '#FFFFFF'
        if tag_name in ('circle', 'rect'):
            node.attrib['fill'] = 'none'
            node.attrib['stroke'] = '#FFFFFF'
    tree.write('tmp-%s.svg' % outname)
    subprocess.call(
        [
            inkscape,
            '--without-gui',
            '--file',
            'tmp-%s.svg' % outname,
            '--export-area-page',
            '--export-png',
            os.path.join(path_out, '%s-on.png' % outname),
            '--export-width',
            '128',
        ]
    )
