#include <gint/display.h>
#include <gint/keyboard.h>
#include <libprof.h>
#include <stdint.h>

#include "config.h"
#include "engine.h"

// Speed in px/us
#define SPEED_FAST 0.000208
#define SPEED_SLOW 0.000104


extern image_t *img_witches[8];
extern image_t *img_battlefields[3];


float speeds[2] = {SPEED_FAST, SPEED_SLOW};

void engine(void)
{
    uint32_t frame = 0;
    uint32_t us_elapsed = 1;

    // Profiling
    prof_t prof_fps = prof_make();
    prof_t prof_engine = prof_make();
    prof_t prof_display = prof_make();

    char witch = 0;
    char mode = 0; // 0 = normal, 1 = focused
    float px = SCREEN_X / 2;
    float py = SCREEN_Y / 2;

    char battlefield = 0;

    while(!keydown(KEY_EXIT))
    {
        // Profiling
        prof_enter(prof_fps);

        // Get keyboard events
        clearevents();


        //*** Some debug inputs ***********************************************
        if(keydown(KEY_F1)) battlefield = 0;
        if(keydown(KEY_F2)) battlefield = 1;
        if(keydown(KEY_F3)) battlefield = 2;
        if(keydown(KEY_1)) witch = 0;
        if(keydown(KEY_2)) witch = 1;
        if(keydown(KEY_3)) witch = 2;
        if(keydown(KEY_4)) witch = 3;
        //*** End debug *******************************************************

        prof_enter(prof_engine);
        // Fast or slow witch
        mode = keydown(KEY_OPTN);
        float base_speed = us_elapsed * speeds[mode] * (
            keydown_any(KEY_LEFT, KEY_RIGHT, 0) &&
            keydown_any(KEY_UP, KEY_DOWN, 0) ? 0.707 : 1.0);

        // Move witch
        if(keydown(KEY_UP))
            py -= base_speed;
        if(keydown(KEY_DOWN))
            py += base_speed;
        if(keydown(KEY_LEFT))
            px -= base_speed;
        if(keydown(KEY_RIGHT))
            px += base_speed;

        prof_leave(prof_engine);


        prof_enter(prof_display);
        // Clear VRAM
        dclear(C_BLACK);

        // Draw battlefield
        dimage(0, 0, img_battlefields[battlefield]);

        // Draw our cute witch
        image_t *w = img_witches[witch * 2 + mode];
        dimage(px - w->width / 2, py - w->height / 2, w);

        prof_leave(prof_display);

        // Print FPS
        dprint(273, 184, C_WHITE, "%i FPS", 1000000 / us_elapsed);
        dprint(273, 194, C_WHITE, "Tot: %i us", us_elapsed);
        dprint(273, 204, C_WHITE, "Eng: %i us", prof_time(prof_engine));
        dprint(273, 214, C_WHITE, "Dsp: %i us", prof_time(prof_display));

        // Update VRAM
        dupdate();

        // Update FPS & frame
        prof_leave(prof_fps);
        us_elapsed = prof_time(prof_fps);
        frame++;
    }
}

void physics(void)
{

}

void graphics(void)
{

}
