/******************************************************************************
 * File: ScopeGuard.hpp
 *
 * Copyright (c) 2023 Qualcomm Technologies, Inc.
 * All Rights Reserved
 * Confidential and Proprietary - Qualcomm Technologies, Inc.
 *
 ******************************************************************************/

#pragma once

#include <functional>

namespace wikitude {
    template<typename Func>
    class ScopeGuard {
    public:
        ScopeGuard(const Func& f)
            : _func(f)
            , _isActive(true) {
        }

        ScopeGuard(Func&& f)
            : _func(std::move(f))
            , _isActive(true) {
        }

        ScopeGuard(ScopeGuard&& rhs)
            : _func(std::move(rhs._func))
            , _isActive(rhs._isActive) {
            rhs._isActive = false;
        }

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

        ~ScopeGuard() {
            if (_isActive)
                _func();
        }

    private:
        Func _func;
        bool _isActive;
    };

    template<typename Func>
    inline ScopeGuard<typename std::decay<Func>::type> OnScopeExit(Func&& f) {
        return ScopeGuard<typename std::decay<Func>::type>(std::forward<Func>(f));
    }
}
