'''
what I do in the test: 
- set beamrate
- choose wire
- choose scan mode
- it seems the method of starting IOC and GUI from python is too complicated... 
	- I tried reading through the pcaspy library but found nothing useful
	- I'll try something called "caproto" library tomorrow - apparently it's good for writing simulations and testing IOCs
	- I'll have to start IOC and GUI myself
	- but after that can I manipulate startscan PV to start a scan from a python script?

- new plan for automation script (if initiating IOC & GUI through python doesn't work): 
	- initiate IOC and GUI manually
	- I want the script to eventually be able to rerun tests for all wire choices, all different beamrates & all scan modes
	- try to RERUN wire scanner for every trial
		- try to restart STARTSCAN PV to 1 (start wirescanner scan) again and again 
	- use time import to measure runtime
	- spit out .csv file 

- update (04/11): I actually figured it out! - now able to run commands as shell subprocesses, and able to do that AND initiate wire scanner run as coroutines/parallel tasks!
- next: measure time of running - all the way from wire scanner initiated to data received

- update (04/14): script can now make a .csv file 
- next: do I want different test modes (e.g. parameters to choose number of wires or beamrate values), or do I want a single program that goes through everything? 
'''

from pcaspy import SimpleServer, Driver
from epics import caput, caget, cainfo, PV
import epics
import subprocess

import sys
import os
import asyncio 
import argparse
import csv
import numpy as np
import time
from datetime import datetime

async def runCommand(command): # helper method to create shell subprocesses
	process = await asyncio.create_subprocess_shell(
		command,
		stdout=asyncio.subprocess.PIPE,
		stderr=asyncio.subprocess.PIPE)
	stdout, stderr = await process.communicate()

	print(f'[{command!r} exited with {process.returncode}]')
	if stdout:
		print(f'[stdout]\n{stdout.decode()}')
	if stderr:
		print(f'[stderr]\n{stderr.decode()}')

async def startWireScanner():
    #commands = "iocConsole sioc-b34-mc03 & pydm -m 'P=WIRE:B34:100:,DEV=WIRE:B34:100, M=MOTR, area=B34,location=100,MAD=CH1,MOC=MOC:B34:MC03,IOC=SIOC:B34:MC03' /u/cd/locng/workspace/pydm/pydm-ws/pydm-ws-git/ws_fastwirescan.py"
    #subprocess.run(commands, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	commands = ["iocConsole sioc-b34-mc03", f'pydm -m "P=WIRE:B34:100:,DEV=WIRE:B34:100, M=MOTR, area=B34,location=100,MAD=CH1,MOC=MOC:B34:MC03,IOC=SIOC:B34:MC03" /u/cd/locng/workspace/pydm/pydm-ws/pydm-ws-git/ws_fastwirescan.py']

	tasks = [runCommand(command) for command in commands]
	await asyncio.gather(*tasks)

async def test(scanner, wsname):
	test_freqs = [1, 5, 10, 20, 50, 120] # testing beamrates; assuming 3-wire step scans for now 
	#setting up containers for .csv columns
	time_data = ["Time [s]"] 
	beamrate_data = ["beamrate [Hz]"]
	wire_used_data = ["Wire Used"]

	epics_startScan = PV(f'{scanner}:STARTSCAN')
	# wait for GUI & IOC initialization to complete
	while(not epics_startScan.connected): 
		await asyncio.sleep(0.1)
		epics_startScan = PV(f'{scanner}:STARTSCAN'); print("value of startScan before starting: ", epics_startScan.get()) 

	# testing scans for all wires 
	# wire input format: (Xwire, Ywire, Uwire) - e.g. (1, 0, 1) = X and U wires used
	#wires = [(1,0,0), (0,1,0), (0,0,1), (1,1,0), (1,0,1), (0,1,1), (1,1,1)]
	wires = [(0,1,0), (0,0,1), (1,1,0)]  # for testing

	for item in wires: 
		epics_useXWire = PV(f'{scanner}:USEXWIRE'); epics_useXWire.put(item[0])
		epics_useYWire = PV(f'{scanner}:USEYWIRE'); epics_useYWire.put(item[1])
		epics_useUWire = PV(f'{scanner}:USEUWIRE'); epics_useUWire.put(item[2])

		useXWire = epics_useXWire.get()
		useYWire = epics_useYWire.get()
		useUWire = epics_useUWire.get()
		
		# keep resetting until the wires are right
		while useXWire != item[0] or useYWire != item[1] or useUWire != item[2]:
			await asyncio.sleep(0.2) 
			epics_useXWire = PV(f'{scanner}:USEXWIRE'); epics_useXWire.put(item[0])
			epics_useYWire = PV(f'{scanner}:USEYWIRE'); epics_useYWire.put(item[1])
			epics_useUWire = PV(f'{scanner}:USEUWIRE'); epics_useUWire.put(item[2])
			useXWire = epics_useXWire.get()
			useYWire = epics_useYWire.get()
			useUWire = epics_useUWire.get()		

		wire_selected = ""
		if useXWire: wire_selected += "X"
		if useYWire: wire_selected += "Y"
		if useUWire: wire_selected += "Z"

		#repeating scans for all frequencies
		for freq in test_freqs:
			#beamrate_data.append(freq)
			wire_used_data.append(wire_selected) #assuming only X-wire used for now 
			
			#setting beamrate parameter
			epics_beamRate_User = PV(f'{scanner}:BEAMRATE_USER'); epics_beamRate_User.put(freq)
			epics_beamRate = PV(f'{scanner}:BEAMRATE'); epics_beamRate.put(freq)
			freq_rbv_user = epics_beamRate_User.get()
			freq_rbv = epics_beamRate.get()
			print("current USER beamrate is: ", freq_rbv_user)
			print("current beamrate is: ", freq_rbv)
			while freq_rbv != freq or freq_rbv_user != freq: 
				await asyncio.sleep(0.2)
				epics_beamRate_User = PV(f'{scanner}:BEAMRATE_USER'); epics_beamRate_User.put(freq)
				epics_beamRate = PV(f'{scanner}:BEAMRATE'); epics_beamRate.put(freq)
				freq_rbv_user = epics_beamRate_User.get()
				freq_rbv = epics_beamRate.get()
				print("current USER beamrate is: ", freq_rbv_user)
				print("current beamrate is: ", freq_rbv)

			beamrate_data.append(freq_rbv_user)
			
			#initiate scan
			epics_startScan = PV(f'{scanner}:STARTSCAN')
			startScan = epics_startScan.get()
			epics_startScan.put(1) # equivalent to pressing start-scan button	

			epics_scanStat = PV(f'{scanner}:SCANSTAT'); scanStat = epics_scanStat.get()
			while(scanStat != 2): #scanStat == 2 means wire scanner is in "scanning" state
				await asyncio.sleep(0.1) 
				scanStat = epics_scanStat.get()
				#print(scanStat, end="\n")

			# start timing once scanner is in SCANNING state
			start = time.perf_counter() 
			print("timing started")	

			epics_scopeFlag = PV(f'{scanner}:SCOPEFLAG'); scopeFlag = epics_scopeFlag.get()
			# waits for scanning - scopeFlag == 0 means Python finished retrieving data
			while(scopeFlag != 0):
				await asyncio.sleep(0.1)
				scopeFlag = epics_scopeFlag.get()

			elapsed_time = time.perf_counter() - start
			print("timing stopped")
			print(f'testing Python timing for {freq} Hz - total runtime: {elapsed_time}')
			time_data.append(elapsed_time)
			await asyncio.sleep(2.0)		

		await asyncio.sleep(2.0)
	
	#prepare .csv table 
	result_data = [beamrate_data, wire_used_data, time_data]
	transposed = np.array(result_data).T.tolist()
	
	# prepare and return .csv file
	now = datetime.now()
	timestring = now.strftime("%Y%m%d_%H%M%S")
	my_path = os.path.abspath(__file__)
	scope_data_dir = os.path.join(os.path.dirname(my_path), 'scope_retrieval_data', f'test_runtime_data')
	if not os.path.exists(scope_data_dir):
		os.makedirs(scope_data_dir)

	csv_filename = os.path.join(scope_data_dir, f"{wsname}_runtime_data__{timestring}.csv")	
	with open(csv_filename, 'w', encoding='UTF8', newline='') as file:
		writer = csv.writer(file)
		writer.writerows(transposed)	

async def run(scanner, wsname):
	task1 = asyncio.create_task(startWireScanner())
	task2 = asyncio.create_task(test(scanner, wsname))

	tasks = [task1]
	await asyncio.gather(*tasks)

if __name__ == "__main__": 
	parser = argparse.ArgumentParser(description="Define host arguments")
	parser.add_argument('scanner', metavar='scanner', type=str, help= 'enter scanner name')
	parser.add_argument('wsname', metavar='wsname', type=str, help= 'enter wsname') # for filename

	args = parser.parse_args()    
	scanner = args.scanner
	wsname = args.wsname
	
	asyncio.run(run(scanner=scanner, wsname=wsname))

#commands = "iocConsole sioc-b34-mc03 & pydm -m 'P=WIRE:B34:100:,DEV=WIRE:B34:100, M=MOTR, area=B34,location=100,MAD=CH1,MOC=MOC:B34:MC03,IOC=SIOC:B34:MC03' /u/cd/locng/workspace/pydm/pydm-ws/pydm-ws-git/ws_fastwirescan.py"
#subprocess.run(commands, shell=True) #starts IOC and PyDM GUI
