import glob
import time
import platform
import byte_triggers as bt
from psychopy import visual, core, event
from psychopy.hardware.keyboard import Keyboard
from sequences import stimuli_manager as sm
from sequences import params as pm
from sequences import instr as it
from sequences.common import get_win_dict

# load window
win_dict = get_win_dict()
win = win_dict['win']
background = win_dict['background']
aspect_ratio = win_dict['aspect_ratio']
win.mouseVisible = False

# setup keyboard for key responses
if platform.system() == 'Linux':
    keyboard = Keyboard()
    keyboard.start()
    adapt_waitKeys = keyboard.waitKeys
else:
    adapt_waitKeys = event.waitKeys

# setup triggers
if pm.use_mock_port:
    pport = bt.MockTrigger()
else:
    pport = bt.ParallelPortTrigger(pm.pport, port_type='pport', delay=10)

# get instructions
instr_rest = it.get_txt('fr', 'instr_rest_fn')
instr = visual.TextStim(
    win,
    text=instr_rest, 
    font="Arial", 
    color='black',  
    height=pm.text_height,
    wrapWidth=1.5,
    alignText="center",
    pos=(0, 0)
)

# get the fixation images (all frames)
w_fns = sorted(glob.glob(f'{pm.spin_wheel_dir}/w*.png'))
w_imgs = [
    visual.ImageStim(win, image=w_fn, size=(0.2, 0.2*aspect_ratio), units="norm")
    for w_fn in w_fns
]
wclock = core.Clock()
rclock = core.Clock()

background.draw()
instr.draw()
win.flip()
adapt_waitKeys(keyList=[pm.key_dict['master_key']])

# trigger to mark the beginning of the resting state
background.draw()
win.callOnFlip(pport.signal, pm.triggers['misc']['block_pause'])
win.flip()
t1 = time.time()
sm.display_wheel(win_dict, wclock, rclock, pm.t_rest, pm.t_rotate, w_imgs)

# trigger to mark the end of the resting state
pport.signal(pm.triggers['misc']['block_pause'])
t2 = time.time()
print(f"Resting state duration: {t2-t1:.2f} seconds")
print("========= End of the resting state =========")
win.close()
core.quit()