
'''
	from volts.topics.process_on import process_on
'''

'''
	env = os.environ.copy ()
	env ["PYTHONPATH"] = ":".join (sys.path)
	process_on (
		env = env
	)
'''

import pexpect
import rich

import atexit
import os

from multiprocessing import Process, Queue

def off (venture):
	try:
		venture.close()
	except Exception:
		pass;
		
def process_on_background (
	process_string,
	
	the_queue = None,
	CWD = None,
	env = {}
):
	the_queue = Queue ()

	print ("process_on_background")

	background_process = Process (
		target = process_on,
		
		args = [ process_string ],
		
		kwargs = {
			"the_queue": the_queue,
			"CWD": CWD,
			"env": env
		}
	)
	
	background_process.start ()
	
	print ('the process started in the background')
	
	# if you'd like to await the process
	# background_process.join()
	
	#result = the_queue.get (timeout = 1)
	#print ("Result from background process:", result)
	
	def parse_queue ():
		proceeds = []
		while not the_queue.empty ():
			proceeds.append (the_queue.get ())
	
		return proceeds;
	
		#return the_queue.get (timeout = 1)
	
	return {
		"process": background_process,
		"queue": parse_queue
	}
	
	
	
	
	

def process_on (
	process_string,
	#
	the_queue = None,
	CWD = None,
	env = {}
):
	print ("process_string:", process_string)
	print ("the_queue:", the_queue)
	print ("CWD:", CWD)
	print ("env:", env)

	if (CWD == None):
		CWD = os.getcwd ()
		
	if (the_queue == None):
		the_queue = Queue ()
		
	report = {
		"journal": []
	}
	p = pexpect.spawn (
		process_string,
		cwd = CWD,
		env = env,
		timeout = None
	)
	def awareness_EOF (p):
		while not p.eof ():
		
			line = p.readline ()

			try:
				UTF8_line = line.decode ('UTF8')
				UTF8_parsed = "yes"
			except Exception:
				UTF8_line = ""
				UTF8_parsed = "no"
				
			try:
				hexadecimal_line = line.hex ()
				hexadecimal_parsed = "yes"
			except Exception:
				hexadecimal_line = ""
				hexadecimal_parsed = "no"
			
			
			line_parsed = {
				"UTF8": {
					"parsed": UTF8_parsed,
					"line": UTF8_line
				},
				"hexadecimal": {
					"parsed": hexadecimal_parsed,
					"line": hexadecimal_line
				}
			};
			
			the_queue.put (line_parsed)
			
			report ["journal"].append (line_parsed)
			
			if (UTF8_parsed == "yes"):
				print ('binary as UTF8:', UTF8_line, end = '')
			else:
				print ('unparseable UTF8 line')
			
			# rich.print_json (data = line_parsed)

	awareness_EOF (p)
	
	atexit.register (off, p)
	
	print ("pexpect spawn started?")
	
	return {
		"process": p,
		"report": report
	}