import appconfig, audio, display, keypad, machine, ntp, sndmixer, system, time, virtualtimers, wifi

settings = appconfig.get("alarm", {"waketime": {"hour": 7, "minute": 30}})
vol = machine.nvs_getint('system', 'volume') or 15
on = 0xFF00FF
off = 0x000000

sndmixer.begin(16)

last_wakeup = 0
running = False
running_channels = []


def sound_on():
    global running, running_channels

    if running:
        new_channels = []

        for freq in [11, 13]:
            chan = sndmixer.synth()
            running_channels.append(chan)
            new_channels.append(chan)
            sndmixer.volume(chan, vol)
            sndmixer.waveform(chan, 0)
            sndmixer.freq(chan, int(440 * (2**(freq/12))))

        display.drawFill(on)
        display.flush()

        for chan in new_channels:
            sndmixer.play(chan)
    return 800


def sound_off():
    global running_channels

    display.drawFill(off)
    display.flush()

    for chan in running_channels:
        sndmixer.stop(chan)

    running_channels = []
    return 800


def wakeup():
    global running, last_wakeup

    if last_wakeup + 600 > time.time():
        return 1000

    current_time = time.localtime()
    if settings['waketime']['hour'] != current_time[3]:
        return 1000

    if settings['waketime']['minute'] != current_time[4]:
        return 1000
    
    last_wakeup = time.time()
    running = True
    return 1000


def snooze(key_index, pressed):
    global running
    if pressed:
        running = False
        sound_off()


if not wifi.status():
    audio.play('/cache/system/wifi_connecting.mp3')
    wifi.connect()
    wifi.wait()
    if not wifi.status():
        audio.play('/cache/system/wifi_failed.mp3')
        time.sleep(6)
        system.launcher()


ntp.set_NTP_time() 

keypad.add_handler(snooze)

virtualtimers.activate()
virtualtimers.new(0,    sound_on)
virtualtimers.new(500,  sound_off)
virtualtimers.new(1000, wakeup)