#include "gibgeneratornode.h"
#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>
#include "scenetree.h"
#include "graphicalnode.h"

void GibGeneratorNode::createGib(GraphicalNode* graphicalPart,
               btCollisionShape *physicsShape,
               float mass,
               const glm::vec3 &pos,
               const glm::vec3 &velocity,
               unsigned int lifeSpan)
{
    if(m_scene != nullptr)
    {
        graphicalPart->moveTo(pos);

        // Create the rigid body object
        btMotionState *motionState = graphicalPart->getMotionState();
        btVector3 localInertia;
        physicsShape->calculateLocalInertia(mass, localInertia);
        btRigidBody *body = new btRigidBody(mass, motionState, physicsShape, localInertia);
        body->setLinearVelocity(btVector3(velocity.x, velocity.y, velocity.z));

        getEngine().getPhysics()->addRigidBody(body);

        m_gibs.push_back(new Gib(body, graphicalPart, getEngine().getTime()+lifeSpan));
        addChild(graphicalPart);
    }
}

void GibGeneratorNode::update()
{
    // TODO : optimisation possible : use some kind of heap stack structure instead of vector
    for(auto it = m_gibs.begin(); it != m_gibs.end();)
    {
        Gib *g = *it;
        if(g->expiration < getEngine().getTime())
        {
            getEngine().getPhysics()->removeCollisionObject(g->body);
            removeChild(g->graphics);
            it = m_gibs.erase(it);
            delete g->graphics;
            delete g;
        }
        else
            ++it;
    }

    // use ContainerNode::update() here instead?
    for(SceneNode* child : m_children)
        child->update();
}
