#include "Prop.h"
#include "debug.h"
#include "game_world.h"
#include "physics_world.h"

Prop* MakeProp(Sprite* sprite, Shape* shape) {
    Prop* self = malloc(sizeof(Prop));
    ASSERT_RETURN(self != NULL, NULL, "Failed to allocate space for Prop instance");
    *self = (Prop) {
        .transform = IdentityTransform,
        .sprite = sprite,
        .rigidbody = NULL,
        .collisionShape = NULL
    };
    self->rigidbody = rigidbody_make(Prop_as_PhysicsEntity(self));
    self->collisionShape = collider_new(Prop_as_PhysicsEntity(self), shape, 0, PHYSICS_LAYER_DEFAULT);
    rigidbody_set_static(self->rigidbody, 1);
    sprite_set_origin(self->sprite, MakeVector(0.5f, 1.0f));
    return self;
}

Prop* SpawnProp(Vector location, Sprite* sprite, Shape* shape, Vector origin) {
    Prop* self = MakeProp(sprite, shape);
    
    self->transform.position
        = rigidbody_get_transform(self->rigidbody)->position
        = location;

    game_world_add_entity(Prop_as_BehaviourEntity(self));
    physics_world_add_entity(Prop_as_PhysicsEntity(self));
    
    sprite_set_origin(self->sprite, origin);
        
    return self;
}

void DestroyProp(Prop* self) {
    sprite_destroy(self->sprite);
    physics_world_remove_entity(Prop_as_PhysicsEntity(self));
    collider_destroy(self->collisionShape);
    rigidbody_destroy(self->rigidbody);
    free(self);
}

void PropStart(Prop* self) {}
void PropUpdate(Prop* self, float deltaTime) {}

void PropDraw(Prop* self) {
    sprite_draw(self->sprite, self->transform);
    shape_draw(collider_get_shape(self->collisionShape), self->transform);
}

void PropOnCollision(Prop* self, Collision collision) {}
void PropOnOverlap(Prop* self, Collider* other) {}

Transform* PropGetTransform(Prop* self) {
    return &self->transform;
}

RigidBody* PropGetRigidBody(Prop* self) {
    return self->rigidbody;
}

void* PropReceiveMessage(Prop* self, MessageID message, void* data) {
    if(message == 1) {
        int damage = *(int*)data;
        game_world_destroy_entity(Prop_as_BehaviourEntity(self));
    }
    return 0;
}
