#include "NetworkResponse.h"
#include "Chunk.h"
#include "Entity.h"
#include "Game.h"

NetworkResponse::NetworkResponse()
{
    adress = 0;
    adressLength = 0;
    broadcast = 0;
    message = 0;
    msgDelete = 0;
    msgLength = 0;
    useBackground = 0;
}

NetworkResponse::~NetworkResponse()
{
    if( msgDelete )
        delete[] message;
    delete[] adress;
}

void NetworkResponse::adressChunck( Chunk* zChunk )
{
    adressLength = 14;
    adress = new char[ adressLength ];
    adress[ 0 ] = 1; // world response
    *(int*)(adress + 1) = zChunk->getDimensionId();
    adress[ 5 ] = 1; // chunck
    Framework::Punkt center = zChunk->getClock();
    *(int*)(adress + 6) = center.x;
    *(int*)(adress + 10) = center.y;
    minPosition = zChunk->getMin();
    maxPosition = zChunk->getMax();
}

void NetworkResponse::adressEntity( Entity* zEntity )
{
    adressLength = 10;
    adress = new char[ adressLength ];
    adress[ 0 ] = 1; // world response
    *(int*)(adress + 1) = zEntity->getCurrentDimensionId();
    adress[ 5 ] = 2; // entity
    *(int*)(adress + 6) = zEntity->getId();
    minPosition = zEntity->getPosition();
    maxPosition = zEntity->getPosition();
}

void NetworkResponse::adressBlock( Block* zBlock )
{
    adressLength = 18;
    adress = new char[ adressLength ];
    adress[ 0 ] = 1; // world response
    *(int*)(adress + 1) = zBlock->getDimensionId();
    adress[ 5 ] = 3; // block
    Framework::Vec3<int> pos = zBlock->getPos();
    *(int*)(adress + 6) = pos.x;
    *(int*)(adress + 10) = pos.y;
    *(int*)(adress + 14) = pos.z;
    minPosition = pos;
    maxPosition = pos;
}

void NetworkResponse::setMessage( char* msg, int length, bool deleteMsg )
{
    message = msg;
    msgLength = length;
    msgDelete = deleteMsg;
}

void NetworkResponse::setUseBackground()
{
    useBackground = 1;
}

void NetworkResponse::sendToAll()
{
    broadcast = true;
}

bool NetworkResponse::isAreaAffected( Framework::Vec3<float> min, Framework::Vec3<float> max ) const
{
    return minPosition.x <= max.x && maxPosition.x >= min.x &&
        minPosition.y <= max.y && maxPosition.y >= min.y &&
        minPosition.z <= max.z && maxPosition.z >= min.z;
}

void NetworkResponse::writeTo( Framework::StreamWriter* zWriter ) const
{
    int total = msgLength + adressLength;
    if( total )
    {
        zWriter->schreibe( (char*)&total, 4 );
        zWriter->schreibe( adress, adressLength );
        zWriter->schreibe( message, msgLength );
    }
}

bool NetworkResponse::isBroadcast() const
{
    return broadcast;
}

bool NetworkResponse::isEmpty() const
{
    return msgLength + adressLength <= 0;
}

bool NetworkResponse::isUseBackground() const
{
    return useBackground;
}