import std.stdio;
import std.datetime;

struct Image {
    void* data;
    int width;
    int height;
    int mipmaps;
    int format;
}

struct Texture2D {
    uint id;
    int width;
    int height;
    int mipmaps;
    int format;
}

struct Vector2 {
    float x;
    float y;
}

struct Color {
    ubyte r;
    ubyte g;
    ubyte b;
    ubyte a;
}

extern(C):
    void InitWindow(int width, int height, const char* title);
    void CloseWindow();

    void SetTargetFPS(int fps);
    void SetRandomSeed(uint seed);
    int GetRandomValue(int min, int max);

    Image LoadImage(const char* file_name);
    void ImageResize(Image* image, int new_width, int new_height);
    Texture2D LoadTextureFromImage(Image image);
    void UnloadImage(Image image);
    void UnloadTexture(Texture2D texture);

    bool WindowShouldClose();
    float GetFrameTime();

    void BeginDrawing();
    void ClearBackground(Color color);
    void DrawTextureV(Texture2D texture, Vector2 position, Color tint);
    void EndDrawing();

const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
const int LOGO_HEIGHT = 64;
const float LOGO_SPEED = 300;

const Color BLACK = Color(0, 0, 0, 255);
const Color WHITE = Color(255, 255, 255, 255);

void main() {
    InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Raylib in D");
    SetTargetFPS(60);
    SetRandomSeed(cast(uint)Clock.currStdTime());

    Image logo_image = LoadImage("./d_logo.png");
    ImageResize(&logo_image, logo_image.width * LOGO_HEIGHT / logo_image.height, LOGO_HEIGHT);
    Texture2D logo_texture = LoadTextureFromImage(logo_image);
    UnloadImage(logo_image);

    float x = GetRandomValue(0, WINDOW_WIDTH - logo_texture.width);
    float y = GetRandomValue(0, WINDOW_HEIGHT - logo_texture.height);

    float dx = LOGO_SPEED * (GetRandomValue(0, 1) ? -1 : 1);
    float dy = LOGO_SPEED * (GetRandomValue(0, 1) ? -1 : 1);

    while (!WindowShouldClose()) {
        float delta_time = GetFrameTime();

        x += dx * delta_time;
        y += dy * delta_time;

        if (x < 0 || (x + logo_texture.width) >= WINDOW_WIDTH - 1)
        {
            dx *= -1;
            x += dx * delta_time;
        }
        if (y < 0 || (y + logo_texture.height) >= WINDOW_HEIGHT - 1)
        {
            dy *= -1;
            y += dy * delta_time;
        }

        BeginDrawing();

        ClearBackground(BLACK);
        DrawTextureV(logo_texture, Vector2(x, y), WHITE);

        EndDrawing();
    }

    UnloadTexture(logo_texture);
    CloseWindow();
}
