#include "Asteroid.h"
#include <Random.h>

Asteroid::Asteroid( int id, Vertex pos, Vertex speed, float rot, float rotS, Model2DData *m2d, Textur2D *textur )
    : Model2DObject()
{
    this->id = id;
    setPosition( pos );
    setSpeed( speed );
    setDrehung( rot );
    setDrehungSpeed( rotS );
    setModel( m2d );
    setTextur( textur );
    alive = true;
    save();
}

bool Asteroid::tick( const WeltInfo &info, double zeit )
{
    if( !alive )
        size -= (float)zeit;
    return __super::tick( info, zeit );
}

Asteroid *Asteroid::split( Vertex pos, Vertex speed, __int64 seed, int asteroidId )
{
    Polygon2D a, b;
    Punkt pa, pb;
    Vertex hp;
    RandomGenerator randG;
    randG.setSeed( seed );
    if( calcHitPoint( pos - speed, speed, hp ) )
    {
        if( zModel()->split( getObjectPos( hp ), getObjectDir( speed ) * 0.1f, ( char* )"", a, b, pa, pb, [ &randG ]() -> double
        {
            return randG.rand();
        } ) )
        {
            impuls( pos - speed, speed * 0.05f );
            hp = ( hp * getSize() ).rotation( getDrehung() ) + getPosition();
            Vertex pav = ( (Vertex)pa ).rotation( getDrehung() ) + getPosition();
            Vertex pbv = ( (Vertex)pb ).rotation( getDrehung() ) + getPosition();
            Array< Polygon2D > *npaA = new Array< Polygon2D >();
            npaA->add( a );
            Model2DData *npdA = new Model2DData();
            npdA->erstelleModell( npaA );
            Array< Polygon2D > *npaB = new Array< Polygon2D >();
            npaB->add( b );
            Model2DData *npdB = new Model2DData();
            npdB->erstelleModell( npaB );
            Asteroid *astr = new Asteroid( asteroidId, pav, getSpeed() * (float)randG.rand(), getDrehung(), getDrehungSpeed() * (float)randG.rand(), npdA, getTextur() );
            setSpeed( getSpeed() * (float)randG.rand() );
            setDrehungSpeed( getDrehungSpeed() * (float)randG.rand() );
            setModel( npdB );
            setPosition( pbv );
            return astr;
        }
    }
    return 0;
}

void Asteroid::save()
{
    backup.pos = getPosition();
    backup.speed = getSpeed();
    backup.rotation = getDrehung();
    backup.rSpeed = getDrehungSpeed();
}

void Asteroid::load()
{
    setPosition( backup.pos );
    setSpeed( backup.speed );
    setDrehung( backup.rotation );
    setDrehungSpeed( backup.rSpeed );
}

void Asteroid::setDead()
{
    alive = false;
    collision = false;
}

bool Asteroid::isDead() const
{
    return size <= 0;
}

int Asteroid::getId() const
{
    return id;
}