import t, c
from stdint import *
from w32.win32base import *
from w32.win32sync import CreateEventA, SetEvent, ResetEvent, WaitForSingleObject


@t.Object
class Event:
    """基于 Windows Event 的事件对象，支持手动/自动重置。

    用法:
        evt: Event = Event(FALSE, FALSE)
        evt.set()
        evt.wait()
    """
    handle: HANDLE
    manual_reset: BOOL

    def __init__(self, manual_reset: BOOL = FALSE, initial_state: BOOL = FALSE):
        self.manual_reset = manual_reset
        self.handle = CreateEventA(NULL, manual_reset, initial_state, NULL)

    def set(self):
        SetEvent(self.handle)

    def clear(self):
        ResetEvent(self.handle)

    def is_set(self) -> BOOL:
        return WaitForSingleObject(self.handle, 0) == WAIT_OBJECT_0

    def wait(self, timeout_ms: ULONG = INFINITE) -> BOOL:
        return WaitForSingleObject(self.handle, timeout_ms) == WAIT_OBJECT_0

    def close(self):
        CloseHandle(self.handle)
