#pragma once

struct sEvent
{
	sEvent() = default;
	~sEvent()
	{
		if (e) CloseHandle(e);
	}

	// event句柄，默认构造为0，Reset()或Set()时自动创建
	HANDLE e = nullptr;

	std::string errStr;
	
	bool Reset()
	{
		if (!e)	// not created yet
			return (nullptr !=(e = CreateEvent(NULL, TRUE, FALSE, NULL)));// ManualReset, InitialState=FALSE
		else
			return bool(ResetEvent(e));
	}

	bool Set()
	{
		if(!e)// not created yet
			return (nullptr !=(e = CreateEvent(NULL, TRUE, TRUE, NULL))); // ManualReset, InitialState=TRUE
		else
			return bool(SetEvent(e));
	}

	int Wait(int timeout)
	{
		uint32_t wait_res = WaitForSingleObject(e, timeout);
		if(wait_res == WAIT_OBJECT_0) {
			errStr.clear();
			return 0;
		}else if(wait_res == WAIT_TIMEOUT) {
			errStr = "Timeout";
			return -1;
		} if (WAIT_FAILED == wait_res) {
			errStr = fmt::format("Fail({})", GetLastError());
			return -2;
		}else if(WAIT_ABANDONED == wait_res){
			errStr = "Abandoned";
			return -3;
		}
		else {
			errStr = fmt::format("Unknown error ({})", wait_res);
			return -4;
		}
	}
	inline operator HANDLE() const
	{
		return e;
	}
	
};

