#include <stdio.h>
#include <math.h>
#include "raylib.h"
#include "raymath.h"

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
#define PLAYER_WIDTH 60
#define PLAYER_HEIGHT 80

#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define CLAMP(var, min, max) (MIN(MAX((var), (min)), (max)))

typedef struct Player {
    Rectangle pos;
    float angle;
} Player;

int main()
{
    InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "kevin la bouteille");
    SetTargetFPS(60);

    Player player = {
        .pos = {
            WINDOW_WIDTH/2,
            WINDOW_HEIGHT/2,
            PLAYER_WIDTH, PLAYER_HEIGHT
        },
        .angle = 0.0f,
    };

    while (!WindowShouldClose()) {
        static float engine_force_left = 0.0f;
        static float engine_force_right = 0.0f;
        const float engine_force_loss = 0.25f;
        const float engine_force_speed = 0.4f;
        const float engine_speed_max = 10.0f;

        if (IsKeyDown(KEY_D)) {
            engine_force_right += engine_force_speed;
        } else {
            engine_force_right -= engine_force_loss;
        }
        engine_force_right = CLAMP(engine_force_right, 0, engine_speed_max);
        if (IsKeyDown(KEY_A)) {
            engine_force_left += engine_force_speed;
        } else {
            engine_force_left -= engine_force_loss;
        }
        engine_force_left = CLAMP(engine_force_left, 0, engine_speed_max);
        player.angle += engine_force_right;
        player.angle -= engine_force_left;

        Vector2 player_direction = {
            cos((player.angle - 90) * PI/180),
            sin((player.angle - 90) * PI/180),
        };
        player_direction = Vector2Scale(player_direction, MAX(engine_force_left, engine_force_right));
        player.pos.x += player_direction.x;
        player.pos.y += player_direction.y;

        // printf("el: %f, er: %f, a: %f\n", engine_force_left, engine_force_right, player.angle);

        // TODO: ne pas augmenter la velociter pendant le boost de l'engine
        //       mais pouvoir qu'en meme avoir la gravité pendant la bouteille
        //       vers le bas ou vers les coté
        static float gravity_velocity = 0.0f;
        const float gravity_force = 1.5f;
        // gravity_velocity += gravity_force;
        gravity_velocity = gravity_force;
        player.pos.y += gravity_velocity;

        // TODO: prendre en consideration l'angle pour la collision,
        if (player.pos.y >= WINDOW_HEIGHT - player.pos.height/2) {
            player.pos.y = WINDOW_HEIGHT - player.pos.height/2;
            gravity_velocity = 0.0f;
        }

        BeginDrawing();
        {
            ClearBackground(RAYWHITE);
            DrawRectanglePro(
                player.pos,
                (Vector2){player.pos.width/2, player.pos.height/2},
                player.angle, RED
            );
            DrawFPS(0, 0);
        }
        EndDrawing();
    }
    return 0;
}
