#include <Core/Common/CoreUtils.h>
#include <Core/Common/EnumUtils.h>
#include <Core/HAL/Display/Display_Private.h>
#include <Core/HAL/Filesystem/Filesystem_Private.h>
#include <Core/JulietInit.h>
#include <Core/Logging/LogManager.h>
#include <Core/Memory/MemoryArena.h>

namespace Juliet
{
    namespace
    {
        bool  IsQuitting = false;
        uint8 SystemInitRefCount[ToUnderlying(JulietInit_Flags::Count)];

        void IncrementSystemRefCount(JulietInit_Flags flag)
        {
            Assert(flag != JulietInit_Flags::None);
            ++SystemInitRefCount[ToUnderlying(flag)];
        }

        void DecrementSystemRefCount(JulietInit_Flags flag)
        {
            Assert(flag != JulietInit_Flags::None);
            Assert(SystemInitRefCount[ToUnderlying(flag)] != 0 && "Trying to decrement ref count but its already 0");

            if (IsQuitting)
            {
                SystemInitRefCount[ToUnderlying(flag)] = 0;
            }
            else
            {
                --SystemInitRefCount[ToUnderlying(flag)];
            }
        }

        bool IsInitialized(JulietInit_Flags flag)
        {
            return SystemInitRefCount[ToUnderlying(flag)] != 0;
        }
    } // namespace

    void JulietInit(JulietInit_Flags flags)
    {
        // Optional systems
        if ((flags & JulietInit_Flags::Display) != JulietInit_Flags::None)
        {
            InitializeDisplaySystem();
            IncrementSystemRefCount(JulietInit_Flags::Display);
        }
    }

    void JulietShutdown()
    {
        IsQuitting = true;
        if (IsInitialized(JulietInit_Flags::Display))
        {
            DecrementSystemRefCount(JulietInit_Flags::Display);
            ShutdownDisplaySystem();
        }
    }

} // namespace Juliet
