#pragma once

#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>

class ScopedSemaphoreLock final
{
public:
    ScopedSemaphoreLock(SemaphoreHandle_t semaphore, TickType_t timeoutTicks)
        : semaphore(semaphore),
          acquired(semaphore != nullptr &&
                   xSemaphoreTake(semaphore, timeoutTicks) == pdTRUE)
    {
    }

    ~ScopedSemaphoreLock()
    {
        if (acquired)
        {
            xSemaphoreGive(semaphore);
        }
    }

    ScopedSemaphoreLock(const ScopedSemaphoreLock &) = delete;
    ScopedSemaphoreLock &operator=(const ScopedSemaphoreLock &) = delete;

    explicit operator bool() const
    {
        return acquired;
    }

private:
    SemaphoreHandle_t semaphore;
    bool acquired;
};
