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

#include "bullet.h"

typedef struct Bullet {
    BulletType type;
    Vector2 pos;
    float time;
    float angle;
} Bullet;

#define BULLET_MAX 5000

Bullet bullets[BULLET_MAX] = {0};

Texture textures[BULLET_COUNT];

void bullet_load()
{
    textures[BULLET_SHURIKEN] = LoadTexture("data/shuriken.png");
    textures[BULLET_MINIGUN] = LoadTexture("data/bullet.png");
}

void bullet_spawn(BulletType type, Vector2 pos, float angle)
{
    for (int i = 0; i < BULLET_MAX; i++) {
        if (bullets[i].time >= EPSILON)
            continue;
        bullets[i].time = 5;
        bullets[i].angle = angle;
        bullets[i].pos.x = pos.x - textures[type].width/2;
        bullets[i].pos.y = pos.y - textures[type].height/2;
        bullets[i].type = type;
        break;
    }
}

void draw_bullets()
{
    for (int i = 0; i < BULLET_MAX; i++) {
        if (bullets[i].time <= EPSILON)
            continue;

        float speed = 50;
        float angle = bullets[i].angle * PI/180;
        Vector2 toward = Vector2Normalize((Vector2) {cos(angle), sin(angle)});
        bullets[i].pos = Vector2Add(bullets[i].pos, Vector2Scale(toward, speed));
        bullets[i].time -= GetFrameTime();

        Texture t = textures[bullets[i].type];
        Rectangle source = {0, 0, t.width, t.height};
        Rectangle dest = {bullets[i].pos.x + t.width/2, bullets[i].pos.y + t.height/2, t.width, t.height};
        Vector2 origin = {t.width/2, t.height/2};

        DrawTexturePro(t, source, dest, origin, bullets[i].angle + 90, WHITE);
    }
}