#!/usr/bin/env python3
'''*****************************************************************************
***  This file is part of Pecunia.                                           ***
***                                                                          ***
***  Copyright (C) 2017, 2018, 2019, 2020, 2021, 2023                        ***
***  John Schneiderman <Licencing _AT_ Schneiderman _DOT_ me>                ***
***                                                                          ***
***  This program is free software: you can redistribute it and/or modify it ***
***  under the terms of the GNU Lesser 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 Lesser General Public License for more details.             ***
***                                                                          ***
***  You should have received a copy of the GNU Lesser General Public License***
***  along with this program. If not, see <http://www.gnu.org/licenses/>.    ***
*****************************************************************************'''
from argparse import ArgumentParser
from datetime import datetime
from os import getcwd, path
from sys import stderr
from traceback import format_exc

from Iso4217 import Currency
from IsoOrgParser import parse
from Templates import CodesTemplateFiller


def __process_arguments():
	parser = ArgumentParser(description="Creates the auto-generated C++ files.")
	parser.add_argument('-c', '--codes', action='store', type=str,
					 default=path.join(getcwd(), "list_one.xml"),
					 help='The file and directory path containing information on ISO 4217 '
					 'currencies. Defaulting to the current directory and the XML file supplied '
					 'by ISO.org')
	return parser.parse_args()


def __generate_codes_files(script_directory_path, currencies):
	codes_filler = CodesTemplateFiller(currencies)
	timestamp = datetime.now()

	with open(path.join(script_directory_path, 'templates', 'Codes.h'), 'r') as \
			code_declaration_template:
		declaration = code_declaration_template.read()
	declaration = declaration.replace('@TIMESTAMP@', timestamp.isoformat())
	declaration = declaration.replace('@ENUM_CODES@', codes_filler.filled_enum_codes())
	declaration = declaration.replace('@NUMBER_OF_CODES@', "{}".format(
		codes_filler.filled_number_of_codes()))

	with open(path.join(script_directory_path, '..', 'external', 'pecunia', 'Codes.h'), 'w') as \
			code_declaration:
		code_declaration.write(declaration)

	with open(path.join(script_directory_path, 'templates', 'Codes.cpp'), 'r') as \
			code_definition_template:
		definition = code_definition_template.read()
	definition = definition.replace('@TIMESTAMP@', timestamp.isoformat())
	definition = definition.replace('@TO_STRING@', codes_filler.filled_to_string())
	definition = definition.replace('@TO_CODE@', codes_filler.filled_to_code())
	definition = definition.replace('@TO_SYMBOL@', codes_filler.filled_to_symbol())
	definition = definition.replace('@MINOR_UNIT_DIGITS@', codes_filler.filled_minor_unit_digits())
	definition = definition.replace(
		'@ALL_CODES_TO_COUNTRIES@',
		codes_filler.filled_all_codes_to_countries()
	)
	definition = definition.replace('@ALL_CODES_TO_NAME@', codes_filler.filled_all_codes_to_names())
	definition = definition.replace('@ALL_ISO_CODES@', codes_filler.filled_all_iso_codes())

	with open(path.join(script_directory_path, '..', 'external', 'pecunia', 'Codes.cpp'), 'w') as \
			code_definition:
		code_definition.write(definition)


if __name__ == "__main__":
	try:
		print("""Generate Pecunia C++ Files Copyright (C) 2020 John Schneiderman
GPCF comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it
under certain conditions; see the COPYING file for details,
or the Free Software Foundation's LGPL.
"""
		)
		args = __process_arguments()
		script_directory_path = path.dirname(__file__)
		currencies = parse(args.codes)
		__generate_codes_files(script_directory_path, currencies)
	except (ValueError, RuntimeError, FileNotFoundError) as error:
		print("Execution Failed: {}".format(error), file=stderr)
		exit(2)
	except Exception as error:
		print("Unexpected error: {err}\n{banner}\n{trace}{banner}".format(err=error,
																		banner='-' * 60,
																		trace=format_exc()),
		file=stderr)
		exit(3)
