#include <assert.h>
#include <utils/logger.h>

#include "game_object_factory.h"

static GameObjectFactory s_objectFactory;
GameObjectFactory* g_objectFactory = (GameObjectFactory*)&s_objectFactory;

void GameObjectFactory::Register(const RuntimeClass* _pRuntimeClass, createGameObject_t _createObjectFunc)
{
    std::map<const RuntimeClass*, createGameObject_t>::iterator it = m_factories.find(_pRuntimeClass);
    assert(it == m_factories.end());

    m_factories.emplace(_pRuntimeClass, _createObjectFunc);

#ifdef _DEBUG
    Msg("Registered object %s", _pRuntimeClass->Name());
#endif // _DEBUG
}

GameObject* GameObjectFactory::Create(const char* classname)
{
    std::map<const RuntimeClass*, createGameObject_t>::iterator it = std::find_if(
        m_factories.begin(),
        m_factories.end(),
        [=](const std::pair<const RuntimeClass*, createGameObject_t>& p)
        {
            return strcmp(p.first->Name(), classname) == 0;
        }
    ); // m_factories.find(classname);
    assert(it != m_factories.end());

    return it->second();
}
