
#include "EntityPage.h"
using namespace Ogre;

namespace Forests {
unsigned long EntityPage::GUID = 0;

void EntityPage::init(PagedGeometry *geom, const Ogre::Any &data)
{
    sceneMgr = geom->getSceneManager();
    rootNode = geom->getSceneNode();
}

EntityPage::~EntityPage()
{
    removeEntities();
}

void EntityPage::addEntity(Entity *entity, const Vector3 &position, const Quaternion &rotation, const Vector3 &scale, const Ogre::ColourValue &color)
{
    Entity* newEntity = entity->clone();
    newEntity->setStatic(true);
    SceneNode *node = rootNode->createChildSceneNode(Ogre::SCENE_STATIC);
    node->setPosition(position);
    nodeList.push_back(node);
    node->attachObject(newEntity);

    //newEntity->setCastShadows(entity->getCastShadows());
    if (hasQueryFlag())
        newEntity->setQueryFlags(getQueryFlag());
    newEntity->setRenderQueueGroup(entity->getRenderQueueGroup());

}

void EntityPage::removeEntities()
{
    std::list<SceneNode*>::iterator i;
    for (i = nodeList.begin(); i != nodeList.end(); ++i)
    {
        SceneNode *node = *i;
        int numObjs = node->numAttachedObjects();
        for (int j = 0; j < numObjs; j++)
        {
            Entity *ent = static_cast<Entity*>(node->getAttachedObject(j));
            if (!ent) continue;
            // remove the entity
            sceneMgr->destroyEntity(ent);
            // and finally the scene node
            sceneMgr->destroySceneNode(node);
        }
    }
    nodeList.clear();
}

void EntityPage::setVisible(bool visible)
{
    std::list<SceneNode*>::iterator i;
    for (i = nodeList.begin(); i != nodeList.end(); ++i){
        SceneNode *node = *i;
        node->setVisible(visible);
    }
}

}
