#include <SDL2/SDL_gpu.h>

#include "physics/dynamic_body.h"
#include "nodes/node.h"
#include "engine/window.h"

DynamicBody::DynamicBody(float size_x, float size_y) {
    if (scene != nullptr) {
        size = Vec2(size_x, size_y);
        bBodyDef.type = b2_dynamicBody;
        bBodyDef.position.Set(worldPosition.x, worldPosition.y);
        bBody = scene->b_world.CreateBody(&bBodyDef);

        //Attach polygon shape
        bShape.SetAsBox(size.x, size.y);
        bFixtureDef.shape = &bShape;
        bFixtureDef.density = density;
        bFixtureDef.friction = friction;

        // Attach the fixture to the body
        bBody->CreateFixture(&bFixtureDef);
    } else {
        Util::log(ERROR, "Failed to initialize physics, scene is nullptr", __FILE__, __LINE__);
    }
}

DynamicBody::~DynamicBody() = default;

void DynamicBody::update() {
    // Call Baseclass update
    Node::update();

    // Call logic updates here
    worldPosition.x = bBody->GetPosition().x;
    worldPosition.y = bBody->GetPosition().y;
    printf("bBody pos: %.3f %.3f\n", worldPosition.x, worldPosition.y);

    // Call render for graphical elements
    render();
}

void DynamicBody::SetWorldPosition(float pos_x, float pos_y) {
    worldPosition.x = pos_x;
    worldPosition.y = pos_y;
    bBody->SetTransform(b2Vec2(worldPosition.x, worldPosition.y), bBody->GetAngle());
}

void DynamicBody::render() {
    SDL_Color color = {255, 255, 255, 100};
    Vec2 position_offset = (worldPosition + localPosition);
    GPU_Rectangle(Window::windowTarget,
                  position_offset.x,
                  position_offset.y,
                  position_offset.x + size.x,
                  position_offset.y + size.y,
                  color);
}