import re
import os
from termcolor import colored

class Program:
	all_jobs_relations = {}

	def __init__(self, name, initialization, parameters, dependencies, job_attrib):
		self.name = name
		self.initialization = initialization
		self.parameters = parameters
		self.dependencies = dependencies
		self.attrib = job_attrib
		self.queue_id = None
		self.batch = None

	def inspect(self, all_attribs = True):
		if isinstance(self.parameters, str):
			program = self.parameters.split(' ')[0]
			command = re.sub("\n","\n\t", self.parameters)
		else:
			program = 'iterative_job'
			command = ' '.join([ b for b in self.parameters])
		if all_attribs:
			all_attribs_string = f"\n#\t{self.attrib}"
		else:
			all_attribs_string = ''
		string = f"> {self.name} > {colored(program, 'red')}\n" # Task id and command
		for line in command.rstrip().split("\n"): string = string + f":\t{colored(line, 'yellow')}\n" # parsed main command
		string = string + f"=\t{colored(self.attrib['exec_folder'], 'blue')}\t{self.attrib['done']}{all_attribs_string}\n" # Path and status execution
		for dep in self.dependencies:  string = string + f"-\t{colored(dep, 'green')}\n" # Task dependencies
		
		return string

	def asign_folder(self, folder_name):
		folder = None
		if self.attrib['folder']:
			if folder_name == 'program_name':
				program = os.path.join(self.attrib['exec_folder'], self.parameters.split(' ', 1)[0]) 			
				count = 0
				folder = f"{program}_{count:04d}"
				all_folders = list(Program.all_jobs_relations.values())
				while folder in all_folders:
					folder = f"{program}_{count:04d}"
					count += 1
			elif folder_name == 'job_name':
				folder = os.path.join(self.attrib['exec_folder'], self.name)
		else:
			folder = self.attrib['exec_folder']

		Program.all_jobs_relations[re.sub('\\)','', self.name)] = folder
		self.attrib['exec_folder'] = folder

	
	def set_dependencies_path(self):
		self.dependencies.sort(reverse = True, key=lambda j: len(j))
		for dep in self.dependencies:
			path =  Program.all_jobs_relations[dep]
			if self.initialization != None: self.initialization = re.sub(dep+'\\)', path, self.initialization) 
			self.parameters = re.sub(dep+'\\)', path, self.parameters)


	def each_add_opt(self):
		if self.attrib.get('additional_job_options') != None:
			for param, val in self.attrib['additional_job_options']:
				yield([param, val])
