// This is copyrighted software. More information is at the end of this file.
#pragma once
#include <SDL_error.h>
#include <SDL_mutex.h>
#include <SDL_version.h>
#include <stdexcept>

/*
 * RAII wrapper for SDL_mutex. Satisfies std's "Lockable" (SDL 2) or "BasicLockable" (SDL 1)
 * requirements so it can be used with std::lock_guard and friends.
 */
class SdlMutex final
{
public:
    SdlMutex()
    {
        if (not mutex_) {
            throw std::runtime_error(SDL_GetError());
        }
    }

    ~SdlMutex()
    {
        SDL_DestroyMutex(mutex_);
    }

    SdlMutex(const SdlMutex&) = delete;
    auto operator=(const SdlMutex&) -> SdlMutex& = delete;

    void lock() noexcept
    {
        SDL_LockMutex(mutex_);
    }

#if SDL_VERSION_ATLEAST(2, 0, 0)
    bool try_lock() noexcept
    {
        return SDL_TryLockMutex(mutex_) == 0;
    }
#endif

    void unlock() noexcept
    {
        SDL_UnlockMutex(mutex_);
    }

private:
    SDL_mutex* mutex_ = SDL_CreateMutex();
};

/*

Copyright (C) 2021 Nikos Chantziaras.

This file is part of SDL_audiolib.

SDL_audiolib is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

SDL_audiolib is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.

You should have received a copy of the GNU Lesser General Public License
along with SDL_audiolib. If not, see <http://www.gnu.org/licenses/>.

*/
