#pragma once

#include <vector>
#include <memory>
#include <functional>
#include <utils.hpp>
#include <object/entity.hpp>
#include <mutex>
#include <unordered_map>
#include <vector>

namespace Game::State {
    class GameState {
        public:
            static GameState& getInstance() { static GameState instance; return instance; }

            // Execute work while holding the GameState mutex to keep access thread-safe.
            template<typename Fn>
            void withEntitiesLocked(Fn&& fn) {
                std::scoped_lock lock(mMutex);
                fn(mEntityMap);
            }

            void wipe();
            Object::Entity* getEntityByName(const std::string& name); // Get an entity by name, returns nullptr if no entity with the name exists
            std::vector<Object::Entity*> getEntitiesSnapshot(bool sortByZIndex = false); // Get a stable snapshot of entity pointers for iteration outside the lock
            void queueEntityRemoval(const std::string& name);
            void processPendingRemovals();

            // Add an entity to the gamestate; returns a pointer to the stored entity.
            Object::Entity* addEntity(std::unique_ptr<Object::Entity> entity);
            bool removeEntity(const std::string& name);

        private:
            mutable std::mutex mMutex; // Shared mutex for thread safety
            std::unordered_map<std::string, std::unique_ptr<Object::Entity>> mEntityMap; // Own entities while allowing O(1) lookup by name
            std::vector<std::string> mPendingRemovals;
    };
}