# Copyright © 2026 Remco van 't Veer
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

import machine, steptime, time

class Snooze:
    loop = 100
    settle = 20000
    threshold = 750
    debug = False
    timer = None
    period = 200
    started_at = None

    def __init__(self, *,
                 sm_id: None,
                 tx_gpio: None,
                 rx_gpio: None,
                 snooze_handler: None):
        machine.Pin(tx_gpio, machine.Pin.IN, machine.Pin.PULL_UP)
        self.st = steptime.STEPTIME(sm_id, tx_gpio)
        self.rx = machine.Pin(rx_gpio, machine.Pin.IN)
        self.snooze_handler = snooze_handler

    def value(self):
        self.st.put(self.loop)
        self.st.put(self.settle)
        return self.st.get()

    def start(self):
        if self.timer is None:
            self.started_at = time.ticks_ms()
            self.timer = machine.Timer(-1)
            self.timer.init(mode = machine.Timer.PERIODIC,
                            period = self.period,
                            callback = self.__callback)

    def stop(self):
        if self.timer is not None:
            self.timer.deinit()
            self.timer = None

    old_value = None

    def __callback(self, _):
        value = self.value()
        self.debug and print("diff", time.ticks_diff(time.ticks_ms(), self.started_at))
        if self.old_value and time.ticks_diff(time.ticks_ms(), self.started_at) > 1000:
            self.debug and print(abs(self.old_value - value))
            if abs(self.old_value - value) > self.threshold:
                self.snooze_handler()
        self.old_value = value

if __name__ == "__main__":
    def snooze():
        print("got snooze")

    t = Snooze(sm_id = 1, tx_gpio = 27, rx_gpio = 26, snooze_handler = snooze)
    t.debug = True
    t.start()

    from sound import Sound
    import time
    sound = Sound(sck_gpio = 1,
                  ws_gpio = 2,
                  sd_gpio = 0)
    sound.play("rooster.wav")

    time.sleep(5)
    sound.stop()
