#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (C) 2020  James Turner
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import argparse
import locale
import os
import sys
import re
import lxml.etree as ET

from catalog import sgprops

PROGNAME = os.path.basename(sys.argv[0])


def processCommandLine():
    params = argparse.Namespace()

    parser = argparse.ArgumentParser(
        usage="""\
%(prog)s [OPTION ...] FGDATA
Copy weather scenario descriptions to the default translation XML""",
        description="""\
""",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        # I want --help but not -h (it might be useful for something else)
        add_help=False)

    parser.add_argument("fgdata", metavar="FGDATA",
                        help="""\
                        location of FGData""")
    parser.add_argument("--help", action="help",
                        help="display this message and exit")

    return parser.parse_args(namespace=params)

# create an xml node with text content
def make_xml_leaf(name, text):
    leaf = ET.Element(name)
    leaf.text = '' if text is None else str(text)
    return leaf

simplify_cre = re.compile(r"\s+")
def simplifyString(input):
    return simplify_cre.sub(" ", input.strip())

def copyWeatherScenarios(fgdata):
    environment_node = sgprops.readProps(os.path.join(fgdata, "Environment", "environment.xml"))
    scenarios = environment_node.getChild('weather-scenarios')
    
    result = ET.Element("PropertyList")

    for s in scenarios.getChildren("scenario"):
        scenarioId = s.getValue("id", None)
        name = simplifyString(s.getValue("name", None))
        desc = simplifyString(s.getValue("description", None))

        result.append(make_xml_leaf(scenarioId + "-name", name))
        result.append(make_xml_leaf(scenarioId + "-desc", desc))

    default_trans_file = os.path.join(fgdata, "Translations", "default", "weather-scenarios.xml")

    doc = ET.ElementTree(result)
    doc.write(default_trans_file, encoding='utf-8', xml_declaration=True, pretty_print=True)


def main():
    global params

    locale.setlocale(locale.LC_ALL, '')
    params = processCommandLine()

    copyWeatherScenarios(params.fgdata)

    sys.exit(0)


if __name__ == "__main__": main()
