#include "ANSTSService.h"
#include <stdexcept>

ANSTSService::ANSTSService(PCWSTR serviceName,
    BOOL canStop,
    BOOL canShutdown,
    BOOL canPauseContinue)
    : CServiceBase(serviceName, canStop, canShutdown, canPauseContinue),
    m_stopping(false)
{
    m_stoppedEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
    if (m_stoppedEvent == nullptr)
    {
        throw std::runtime_error("Failed to create stop event, error: " + std::to_string(GetLastError()));
    }
}

ANSTSService::~ANSTSService()
{
    if (m_workerThread.joinable()) {
        m_workerThread.join();
    }

    if (m_stoppedEvent)
    {
        CloseHandle(m_stoppedEvent);
        m_stoppedEvent = nullptr;
    }
}

void ANSTSService::OnStart(DWORD argc, LPWSTR* argv)
{
    WriteEventLogEntry(L"ANSTSService starting...", EVENTLOG_INFORMATION_TYPE);

    // Start service logic in a dedicated thread
    m_workerThread = std::thread([this]() { ServiceWorkerThread(); });
}

void ANSTSService::ServiceWorkerThread()
{
    while (!m_stopping.load())
    {
        // Perform main task
        ::Sleep(2000); // Simulate work
        WriteEventLogEntry(L"ANSTSService performing task...", EVENTLOG_INFORMATION_TYPE);

    }

    SetEvent(m_stoppedEvent); // Notify OnStop we're finished
}

void ANSTSService::OnStop()
{
    WriteEventLogEntry(L"ANSTSService stopping...", EVENTLOG_INFORMATION_TYPE);

    m_stopping = true;

    if (WaitForSingleObject(m_stoppedEvent, INFINITE) != WAIT_OBJECT_0)
    {
        throw std::runtime_error("Wait for service stop failed, error: " + std::to_string(GetLastError()));
    }

    if (m_workerThread.joinable()) {
        m_workerThread.join();
    }
}
