from stimuli.audio import Sound, Tone
from psychopy import event, visual
from sequences.common import get_win_dict
import time

def detection_threshold(sound):
    print('starting calibration')
    volume = 0
    while True:
        if volume >= 100:
            print('calibration stopped: volume reached maximum')
            time.sleep(1)
            del sound
            return volume

        keys = event.getKeys()
        print(f'keys: {keys}')
        if keys:
            print('calibration stopped by user')
            time.sleep(1)
            del sound
            return volume

        time.sleep(2)
        volume += 5
        print(f'-- calibrating at volume: {volume}')
        sound.volume = volume
        sound.play()
        

# sound = None
win_d = get_win_dict()
win = win_d['win']
aspect_ratio = win_d['aspect_ratio']
background = win_d['background']

instr = visual.TextStim(win, text="Press any key to start calibration", color='black')

background.draw()
instr.draw()
win.flip()
event.waitKeys()

sound = Sound('/Users/pironn/Documents/PhD/experiment/crossmodal-sequences/data/input/sounds/seq_sounds/tuba.wav')
volume = detection_threshold(sound)
print(f'Calibration complete. Detected volume: {volume}')