import argparse
import os

from py_autoflow.main_modules import *

## TYPES
def single_list(string): return string.strip().split(',')
def var_list(string, sep1=";", sep2="="): return [sublst.split(sep2) for sublst in string.strip().split(sep1)]

## MODULES
def autoflow(args=None):
	if args == None: args = sys.argv[1:]
	parser = argparse.ArgumentParser(description='Usage: AutoFlow -w worflow_file -c n_cpus')

	parser.add_argument('-A', "--additional_job_options", dest="additional_job_options", default=None, type=var_list,
		help="Additional option in queue system jobs. Format: 'parameter=value;...'")
	parser.add_argument('-b', "--batch", dest="batch", default=False, action="store_true",
		help="Workflow execution using batch")
	parser.add_argument('-c', "--cpus", dest="cpus", default=16, type=int,
		help="Max number of CPUs that can be used in all workflow.")    
	parser.add_argument('-C', "--comment_main_command", dest="comment", default=False, action="store_true",
		help="Workflow execution using batch")
	parser.add_argument('-d', "--external_dependencies", dest="external_dependencies", default=[], type=single_list,
		help="The workflow will start when indicated jobs are finished on queue system. Format: \'id1,id2,id3..\'")
	parser.add_argument('-e', "--extended_logging", dest="extended_logging", default=False, action="store_true",
		help="If set the command /usr/bin/time will be used instead of shell built-in version. Data will be saved in process_data file of task folder")
	parser.add_argument('-f', "--force", dest="retry", default=False, action="store_true",
		help="Execute all jobs, including any job commented with %%")
	parser.add_argument('-g', "--graph", dest="graph", default=None, 
		help="Draw a chart for the template. The workflow is not executed \'t\' use TIDs for box names \'f\' use folder names for boxes.")
	parser.add_argument('-i', "--job_identifier", dest="identifier", default=None, 
		help="Identifier tag for each launching script")
	parser.add_argument('-k', "--key_name", dest="key_name", default=False, action="store_true",
		help="Use job names as folder names")
	parser.add_argument('-L', "--linked_folders", dest="linked_folders", default=False, action="store_true",
		help="Use hashed names in folders with symbolic links")
	parser.add_argument('-m', "--memory", dest="memory", default='16gb', 
		help="Max memory that can be allocated in a task.")
	parser.add_argument('-n', "--node_type", dest="node_type", default=None, 
		help="Apply constraint attribute to tasks.")
	parser.add_argument('-o', "--output", dest="output", default='exec', 
		help="Apply constraint attribute to tasks.")
	parser.add_argument('-r', "--resources", dest="resources", default=None, 
		help="Path to resources file.")
	parser.add_argument('-s', "--use_ntasks", dest="use_ntasks", default=False, action="store_true",
		help="Use several nodes on execution")
	parser.add_argument('-S', "--show_submit_command", dest="show_submit_command", default=False, action="store_true",
		help="Show the command line used to submit the job")
	parser.add_argument('-t', "--time", dest="time", default='20:00:00', 
		help='Max time that can be needed in a task. Format: dd-hh:mm:ss')
	parser.add_argument('-u', "--use_multinode", dest="use_multinode", default=0, type=int, 
		help='For use several nodes on execution')
	parser.add_argument('-v', "--verbose", dest="verbose", default=0, action="count",
		help="Show info without launching jobs")
	parser.add_argument('-V', "--Variables", dest="Variables", default=None, type=lambda x: var_list(x, ',', '='),
		help="Variables to be parsed on template. Format: \'$variable_name1=value1,$variable_name2=value2,...\'")
	parser.add_argument('-w', "--workflow", dest="workflow", default=None, 
		help='Input workflow file')
	parser.add_argument("--white_list", dest="white_list", default=[], type = single_list, 
		help='Task names (could be regexp), comma separated, that will be allowed to execute')
	parser.add_argument("--black_list", dest="black_list", default=[], type = single_list, 
		help='Task names (could be regexp), comma separated, that will NOT be allowed to execute')
	parser.add_argument("--sleep", dest="sleep_time", default=0, type=float, 
		help='Time in seconds to wait between jobs queue submmit')

	opts = parser.parse_args(args)
	main_autoflow(opts)


def flow_logger(args=None):

	if args == None: args = sys.argv[1:]
	parser = argparse.ArgumentParser(description='Usage: flow_logger [options]')

	parser.add_argument("-e", "--workflow_execution", dest="workflow_execution", default=os.getcwd(), 
		help='Path to workflow directory')
	parser.add_argument("-E", "--error", dest="error", default=None, 
		help='Write detected error timestamp of TASK_NAME to log')
	parser.add_argument("-S", "--set", dest="set", default=None, 
		help='Write start timestamp of TASK_NAME to log')
	parser.add_argument("-s", "--start", dest="start", default=None, 
		help='Write start timestamp of TASK_NAME to log')
	parser.add_argument("-f", "--finish", dest="finish", default=None, 
		help='Write finish timestamp of TASK_NAME to log')
	parser.add_argument("-r", "--report", dest="report", default=None, 
		help='List the status of launched tasks')
	parser.add_argument('-w', "--workflow_finished", dest="workflow_status", default=False, action="store_true",
		help="When set, logger assumes that the workflow has ended")
	parser.add_argument('-n', "--no_size", dest="no_size", default=False, action="store_true",
		help="When set, logger don't compute the workflow folder sizes")
	parser.add_argument('-l', "--launch_failed_jobs", dest="launch_failed_jobs", default=False, action="store_true",
		help="Launch jobs tagged as ABORT and NOT. This option only works when the -w flag is enabled")
	parser.add_argument('-p', "--pending", dest="pending", default=False, action="store_true",
		help="Launch jobs tagged as NOT. This option only works when the -w flag is enabled")
	parser.add_argument('-b', "--batch", dest="batch", default=False, action="store_true",
		help="Workflow execution using batch")
	parser.add_argument("--sleep", dest="sleep_time", default=0, type=float, 
		help='Time in seconds to wait between jobs queue submmit')
	parser.add_argument("--raw", dest="raw", default=False, action="store_true", 
		help='When used with report flag, the output is raw python output instead of formatted table')

	opts = parser.parse_args(args)
	out = main_flow_logger(opts)
	return out
