#! /usr/bin/env python3

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

parser = argparse.ArgumentParser()
parser.add_argument('--overlay', dest='overlay', type=str)
args = parser.parse_args()

# get themes
errors = False
themes = []
for dirname in sorted(os.listdir('static')):
    config = os.path.join('static', dirname, 'config.json')
    if not os.path.exists(config):
        continue
    theme = json.load(open(os.path.join('static', dirname, 'config.json'), encoding='utf-8'))
    theme['id'] = dirname
    if not 'variables' in theme:
        theme['variables'] = {}
    if not theme['variables'].get('css_variant'):
        theme['variables']['css_variant'] = dirname
    if 'pwa_display' not in theme['variables']:
        theme['variables']['pwa_display'] = 'standalone'
    if os.path.exists(os.path.join('static', dirname, 'extra.js')):
        theme['variables']['no_extra_js'] = False
    else:
        theme['variables']['no_extra_js'] = True
    if os.path.exists(os.path.join('static', dirname, 'backoffice.scss')) or os.path.exists(
        os.path.join('static', dirname, 'backoffice.css')
    ):
        theme['variables']['portal_agent_extra_css'] = '/static/%s/backoffice.css' % dirname
    else:
        theme['variables']['portal_agent_extra_css'] = None
    if 'included_js_libraries' not in theme['variables']:
        theme['variables']['included_js_libraries'] = ['jquery.js']
    if args.overlay:
        theme['module'] = 'publik-base'
        theme['overlay'] = args.overlay

    # validation checks
    theme_color = theme['variables'].get('theme_color')
    if theme_color and not re.match(r'#[0-9a-fA-F]{6}$', theme_color):
        print('E: invalid theme color for %s (%s)' % (dirname, theme_color), file=sys.stderr)
        errors = True
    if theme.get('settings'):
        for settings_app in theme['settings']:
            if settings_app not in ('authentic2', 'combo', 'fargo', 'wcs'):
                print('E: unknown application key for %s (%s)' % (dirname, settings_app), file=sys.stderr)
                errors = True
                continue
            if settings_app == 'combo':
                for settings_key in theme['settings'][settings_app].keys():
                    if settings_key not in (
                        'COMBO_ASSET_SLOTS.update',
                        'COMBO_CELL_ASSET_SLOTS.update',
                        'COMBO_CELL_TEMPLATES.update',
                        'COMBO_DASHBOARD_ENABLED',
                        'COMBO_DASHBOARD_NEW_TILE_POSITION',
                        'COMBO_MAP_ATTRIBUTION',
                        'COMBO_MAP_DEFAULT_POSITION',
                        'COMBO_MAP_LAYER_ASSET_SLOTS.update',
                        'COMBO_MAP_MAX_BOUNDS',
                        'COMBO_MAP_TILE_URLTEMPLATE',
                        'COMBO_PUBLIC_TEMPLATES.update',
                        'COMBO_SEARCH_SERVICES.update',
                        'JSON_CELL_TYPES.update',
                        'PWA_NOTIFICATION_BADGE_URL',
                        'PWA_NOTIFICATION_ICON_URL',
                        'WCS_CATEGORY_ASSET_SLOTS',
                        'WCS_FORM_ASSET_SLOTS',
                    ):
                        print(
                            'E: unknown settings key for %s (%s)' % (dirname, settings_key), file=sys.stderr
                        )
                        errors = True

    themes.append(theme)

if errors:
    sys.exit(1)

# get parameters
parameters = {'primary-color': {'type': 'color'}}
if os.path.exists('help/fr/misc-scss.page'):
    tree = ET.parse('help/fr/misc-scss.page')
    for element in tree.findall('.//{http://projectmallard.org/1.0/}tr'):
        name, description, value = element.findall('{http://projectmallard.org/1.0/}td')
        name = ''.join(name.itertext()).strip('$')
        description = ''.join(description.itertext()).strip('$')
        value = ''.join(value.itertext()).strip('$')
        parameter_type = 'text'
        if (
            value.startswith('#')
            or value in ('white', 'black')
            or name.endswith('color')
            or name.endswith('background')
        ):
            parameter_type = 'color'
        if value.endswith('px') or value.endswith('rem') or name.endswith('size'):
            parameter_type = 'size'
        if value in ('true', 'false'):
            parameter_type = 'boolean'
        if name.endswith('weight'):
            parameter_type = 'weight'
        if name.endswith('family'):
            parameter_type = 'family'
        parameters[name] = {
            'type': parameter_type,
            'description': description,
        }


with open('themes.json', 'w', encoding='utf-8') as fd:
    json.dump({'themes': themes, 'parameters': parameters}, fd, indent=2, sort_keys=True)
