import os,sys

from py_autoflow.queue_manager import QueueManager

class BashManager(QueueManager):
	priority = 1

	@classmethod
	def isavailable(cls, options):
		return True

	def __init__(self, exec_folder, options, commands):
		super().__init__(exec_folder, options, commands)
		self.queued = []
		self.count = 0
		self.pids = {}
		self.path2execution_script = os.path.join(self.exec_folder, 'execution.sh') 
		self.create_file('execution.sh', self.exec_folder)
		self.write_file('execution.sh', '#! /usr/bin/env bash')

	def launch_all_jobs(self):
		super().launch_all_jobs()
		self.close_file('execution.sh', 0o755)
		self.system_call(f"{self.path2execution_script} > {os.path.join(os.path.dirname(self.path2execution_script),'output')} & ", self.exec_folder)

	def write_header(self, id, node, sh):
		return None

	def submit_job(self, job, ar_dependencies):
		self.write_file('execution.sh','')
		if len(ar_dependencies) > 0: 
			for dep in ar_dependencies:
				cmd = f"wait \"$pid{self.pids[dep]}\"\nif [ $? -ne 0 ]\nthen \n\techo \"{job.name} failed\"\n\texit\nfi"
				self.write_file('execution.sh', cmd) 
		self.write_file('execution.sh', f"cd {job.attrib['exec_folder']}")
		self.write_file('execution.sh', f"./{job.name}.sh &> task_log & pid{self.count}=$!")
		self.pids[job.name] = self.count
		self.count += 1
		self.queued.append(job.name) # For dependencies purposes
		return None

	def get_queue_system_id(self, shell_output):
		return None