"""Tests for ShutdownHandler."""

import threading
import time

from brinkhaustools.common.shutdown import ShutdownHandler


def test_initial_state():
    h = ShutdownHandler(install_signal_handlers=False)
    assert not h.is_shutdown()


def test_trigger_immediate():
    h = ShutdownHandler(install_signal_handlers=False)
    h.trigger()
    assert h.is_shutdown()


def test_trigger_delayed():
    h = ShutdownHandler(install_signal_handlers=False)
    h.trigger(delay_sec=0.1)
    assert not h.is_shutdown()
    time.sleep(0.2)
    assert h.is_shutdown()


def test_shutdown_hook_called():
    h = ShutdownHandler(install_signal_handlers=False)
    called = []
    h.register_hook(lambda: called.append(True))
    h.trigger()
    assert called == [True]


def test_hooks_execute_once():
    h = ShutdownHandler(install_signal_handlers=False)
    counter = []
    h.register_hook(lambda: counter.append(1))
    h.trigger()
    h.trigger()
    assert len(counter) == 1


def test_sleep_interrupted():
    h = ShutdownHandler(install_signal_handlers=False)
    threading.Timer(0.1, h.trigger).start()
    start = time.monotonic()
    interrupted = h.sleep(5.0)
    elapsed = time.monotonic() - start
    assert interrupted
    assert elapsed < 1.0


def test_reset_for_testing():
    h = ShutdownHandler(install_signal_handlers=False)
    h.trigger()
    assert h.is_shutdown()
    h.reset_for_testing()
    assert not h.is_shutdown()


def test_event_property():
    h = ShutdownHandler(install_signal_handlers=False)
    assert isinstance(h.event, threading.Event)
    h.trigger()
    assert h.event.is_set()
