#ifndef CPARTICLEBOUNCEAFFECTOR_H_INCLUDED
#define CPARTICLEBOUNCEAFFECTOR_H_INCLUDED

#include "os.h"
#include "IParticleSystemSceneNode.h"
namespace irr
{
namespace scene
{

// Thanx to vitek
// http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=15605&highlight=emitter
class CParticleBounceAffector : public IParticleAffector
{

public:
    CParticleBounceAffector(IParticleSystemSceneNode* ps, ISceneManager* msmgr, const core::plane3df& plane, const f32 bounce)
    : ParticleSystem(ps)
        , SceneManager(msmgr)
        , Plane(plane)
        , mBounce(bounce)
    {}
    virtual void affect(u32 now, SParticle* particlearray, u32 count)
    {
        if (LastTime==0)
            LastTime = now;
        u32 timediff = now - LastTime;
        LastTime=now;

        u32 p;
        for (p = 0; p < count; ++p)
        {
            SParticle& particle = particlearray[p];

            f32 distanceToPlane = Plane.getDistanceTo(particle.pos);

            if (distanceToPlane < 0.f)
            {
                f32  a = distanceToPlane; //Plane.Normal.dotProduct(particle.pos) + distanceToPlane;
//                printf("a=%f\n",a);
//                if (a > 0.0)
//                {
                    // well, we collided
                    vector3df direction = particle.pos += particle.vector* timediff;
                    //;Nun wirds interessant
                    vector3df directionPart = direction * (- a / direction.dotProduct( Plane.Normal ));


                    // reflect direction vector
                    particle.vector = (particle.vector - (2.0 * particle.vector.dotProduct( Plane.Normal ) * Plane.Normal)) * mBounce;


                      // set new position
                    particle.pos += (particle.vector * timediff);
//                    particle.pos += (particle.pos + ( directionPart )) + (((directionPart) - direction) * mBounce);

                    printf("vector after (%f,%f,%f)\n",particle.vector.X,particle.vector.Y,particle.vector.Z);

//                }

            }
        }
    }

    E_PARTICLE_AFFECTOR_TYPE getType() const { return EPAT_GRAVITY; }



    void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options)
    {
//        out->addColor("When", When);
    }

    s32 deserializeAttributes(s32 startIndex, io::IAttributes* in, io::SAttributeReadWriteOptions* options)
    {
/*
        const char* name = in->getAttributeName(startIndex);
        if (!name || strcmp(name, "When"))
            return startIndex; // attribute not valid
        When = in->getAttributeAsInt(startIndex);

        ++startIndex;
*/
        return startIndex;
    }

private:
    IParticleSystemSceneNode* ParticleSystem;
    ISceneManager* SceneManager;
    f32 mBounce;
    u32 LastTime;
    core::plane3df Plane;
};
}
}


#endif // CPARTICLEBOUNCEAFFECTOR_H_INCLUDED
