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

'''
This script simply uses the Manager class to manage simulations of a folder.
'''

import argparse
import glob
import os

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

def addArguments(parser):
	parser.add_argument('--errors', type = str, help = 'path to the file which will contain the simulations that led to an error')
	parser.add_argument('--settings-file', type = str, default = 'settings.json', help = 'name of the file to create to store the settings of each simulation (extract only)')
	parser.add_argument('--no-settings-file', action = 'store_false', dest = 'store_settings', help = 'do not store the settings of the extracted simulations')
	parser.add_argument('mode', choices = ['add', 'delete', 'extract'], help = 'mode to use (addition, deletion or extraction)')
	parser.add_argument('simulations', type = str, help = 'path to the file describing the simulations to treat, or to a folder containing the simulations')

def main(args):
	modes_configs = {
		'add': {
			'readonly': False,
			'action': 'Adding',
			'done': 'added',
			'function': 'batchAdd',
			'args': {}
		},

		'delete': {
			'readonly': False,
			'action': 'Deleting',
			'done': 'deleted',
			'function': 'batchDelete',
			'args': {}
		},

		'extract': {
			'readonly': True,
			'action': 'Extracting',
			'done': 'extracted',
			'function': 'batchExtract',
			'args': {'settings_file': args.settings_file} if args.store_settings else {}
		}
	}

	folder = utils.findFolder()

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

	with Manager(folder, readonly = modes_configs[args.mode]['readonly']) as manager:
		if os.path.isfile(args.simulations):
			simulations = jsonfiles.read(args.simulations, allow_generator = True)

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

			# We want a list of simulations dictionaries
			# Then, we test the first item: if it seems to not contain global settings, we add them
			if not(type(simulations[0]) is dict) or not('settings' in simulations[0]):
				simulations = [{'folder': '', 'settings': s} for s in simulations]

		else:
			simulations = [os.path.dirname(path) for path in glob.glob(os.path.join(args.simulations, '**', args.settings_file), recursive = True)]
			modes_configs[args.mode]['function'] += 'FromFolder'
			modes_configs[args.mode]['args']['settings_file'] = args.settings_file

		if not(simulations):
			print('The list of simulations is empty')
			return

		ui = UI()

		infos_line = ui.addTextLine(f'{modes_configs[args.mode]["action"]} {string.plural(len(simulations), "simulation", "simulations")}…')
		progress_bar = ui.addProgressBar(len(simulations))

		issues = getattr(manager, modes_configs[args.mode]['function'])(simulations, callback = progress_bar.update, **modes_configs[args.mode]['args'])

		ui.removeItem(progress_bar)

		if issues and args.errors:
			jsonfiles.write(issues, args.errors)

		final_update = string.plural(len(simulations) - len(issues), 'simulation', 'simulations')
		final_update += ' ' + modes_configs[args.mode]['done']

		if issues:
			final_update += ', ' + string.plural(len(issues), 'error', 'errors')

		infos_line.text = final_update

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