from pygui.backend.models.stability_detector import (
    STATE_IDLE,
    STATE_RAMP,
    STATE_SET,
    StabilityDetector,
)

SET_POINT = 149.0

def make():
    return StabilityDetector(idle_below = 50.0, tolerance=1.0, settle_seconds=2.0)

def test_idle_when_cold():
    d = make()
    assert d.update(avg=25.0, time=0.0, set_point=SET_POINT) == STATE_IDLE

def test_ramp_while_far_from_setpoint():
    d = make()
    d.update(avg=100.0, time=0.0, set_point=SET_POINT)

def test_ramp_until_settle_time_elapses():
    d = make()
    assert d.update(avg=149.2, time=0.0, set_point=SET_POINT) == STATE_RAMP
    assert d.update(avg=148.9, time=0.0, set_point=SET_POINT) == STATE_RAMP

def test_set_after_holding_near_setpoint():
    d = make()
    d.update(avg=149.2, time=0.0, set_point=SET_POINT)
    d.update(avg=148.9, time=1.0, set_point=SET_POINT)
    assert d.update(avg=149.0, time=2.5, set_point=SET_POINT) == STATE_SET


def test_back_to_ramp_on_disturbance():
    d = make()
    for t in (0.0, 1.0, 2.5):
        d.update(149.0, t, set_point=SET_POINT)
    assert d.update(avg=160.0, time=3.0, set_point=SET_POINT) == STATE_RAMP
