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

'''
This script simply uses the Manager class to transform some simulations.
'''

import argparse

from hateno.manager import Manager
from hateno.ui import UI
from hateno.utils import utils, jsonfiles, string

def addArguments(parser):
	parser.add_argument('transform_script', type = argparse.FileType('r'), help = 'path to the script where the transformation function is defined')
	parser.add_argument('simulations_list', type = str, nargs = '?', help = 'path to the file where the simulations list to transform can be found')

def main(args):
	folder = utils.findFolder()

	if folder is None:
		print('No Hateno folder found')
		return

	with Manager(folder) as manager:
		ui = UI()

		simulations = None
		if args.simulations_list:
			simulations = jsonfiles.read(args.simulations_list, allow_generator = True)

			if not(type(simulations) is list):
				simulations = [simulations]

			# We only want a list of simulations settings, without the global settings
			# Then, we test the first item: if it seems to contain global settings, we remove them
			if type(simulations[0]) is dict and 'settings' in simulations[0]:
				simulations = [s['settings'] for s in simulations]

		n_simulations = len(simulations) if not(simulations is None) else manager.getSimulationsNumber()

		infos_line = ui.addTextLine(f'Transforming {string.plural(n_simulations, "simulation", "simulations")}…')
		progress_bar = ui.addProgressBar(n_simulations)

		module = utils.loadModuleFromFile(args.transform_script.name)

		manager.transform(module.transform, simulations, callback = progress_bar.update)

		ui.removeItem(progress_bar)
		infos_line.text = f'{string.plural(n_simulations, "simulation", "simulations")} transformed'

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description = 'Manage the simulations stored in a given folder.')
	addArguments(parser)
	main(parser.parse_args())
