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

'''
This script uses the Maker class to extract/generate simulations.
'''

import os
import argparse

from hateno import jsonfiles, string
from hateno.maker import Maker, MakerUI

def addArguments(parser):
	parser.add_argument('--config', type = str, required = True, help = 'name of the config to use')
	parser.add_argument('--copy-list', type = str, help = 'path to use to save a copy of the list of the simulations to generate')
	parser.add_argument('--merge-copy', action = 'store_true', help = 'if the copy file already exists, merge instead of replace')
	parser.add_argument('--save-unknown', type = str, help = 'path to the file where simulations that failed to be generated must be stored')
	parser.add_argument('--pause-file', type = str, default = 'maker.state', help = 'path to the file to read/write for the pauses')
	parser.add_argument('folder_path', type = str, help = 'path to the simulations folder')
	parser.add_argument('simulations_list', type = argparse.FileType('r'), help = 'path to the file where the simulations list can be found')

def action(args):
	simulations = jsonfiles.read(args.simulations_list.name, allow_generator = True)

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

	if args.copy_list:
		simulations_to_write = simulations[:]

		if os.path.isfile(args.copy_list) and args.merge_copy:
			simulations_to_write += jsonfiles.read(args.copy_list)

		jsonfiles.write(list(simulations_to_write), args.copy_list)

	with Maker(args.folder_path, args.config) as maker:
		ui = MakerUI(maker)

		if os.path.isfile(args.pause_file):
			maker.pause()
			maker.loadState(args.pause_file)
			os.unlink(args.pause_file)

			unknown_simulations = maker.resume()

		else:
			unknown_simulations = maker.run(simulations)

		if maker.paused:
			maker.saveState(args.pause_file)

		elif unknown_simulations and args.save_unknown:
			jsonfiles.write(unknown_simulations, args.save_unknown)

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description = 'Extract, and generate if needed, some simulations.')
	addArguments(parser)
	action(parser.parse_args())
