#include <softbus_core/platform/PlatformSignal.h>

#ifdef SOFTBUS_PLATFORM_WINDOWS
#include <windows.h>
#else
#include <csignal>
#endif

namespace softbus::core {

std::atomic<bool> PlatformSignal::stopRequested_{false};

#ifdef SOFTBUS_PLATFORM_WINDOWS
namespace {
    BOOL WINAPI consoleHandler(DWORD signal)
    {
        if (signal == CTRL_C_EVENT || signal == CTRL_BREAK_EVENT || signal == CTRL_CLOSE_EVENT) {
            PlatformSignal::requestStop();
            return TRUE;
        }
        return FALSE;
    }
}
#endif

void PlatformSignal::install(Handler handler)
{
    stopRequested_.store(false);
#ifdef SOFTBUS_PLATFORM_WINDOWS
    SetConsoleCtrlHandler(consoleHandler, TRUE);
#else
    std::signal(SIGINT, [](int) { requestStop(); });
    std::signal(SIGTERM, [](int) { requestStop(); });
#endif
    (void)handler;
}

bool PlatformSignal::shouldStop()
{
    return stopRequested_.load();
}

void PlatformSignal::requestStop()
{
    stopRequested_.store(true);
}

} // namespace softbus::core
