#include "gkernel.h"

static volatile int speedCounter = 0;
static volatile unsigned int gTime = 0;

static void IncrementSpeedCounter()
{
	speedCounter++;
	gTime++;
}
END_OF_FUNCTION(IncrementSpeedCounter);



CGKernel::CGKernel()
{
    LOCK_VARIABLE(speedCounter);
    LOCK_FUNCTION(IncrementSpeedCounter);
    install_int_ex(IncrementSpeedCounter, BPS_TO_TIMER(KERNEL_FPSQ));
    gfont = alfont_load_font(KERNEL_FONT_NAME);
    alfont_set_font_size(gfont, KERNEL_FONT_SIZE);
    page1 = create_video_bitmap(SCREEN_W, SCREEN_H); // Page Flip
    page2 = create_video_bitmap(SCREEN_W, SCREEN_H);  // Page Flip
    activePage = page2;

    heroi = new CHeroi(0, 0, &gTime);
}



CGKernel::~CGKernel()
{
	delete heroi;
    destroy_bitmap(page1);
    destroy_bitmap(page2);
    alfont_destroy_font(gfont);
    remove_int(IncrementSpeedCounter);
}


/*! O loop principal do jogo.
 */
void CGKernel::Go()
{
    speedCounter = 0;
    gameOver = false;
    while(!gameOver)
    {
        while(speedCounter > 0)
        {
            UpdateLogic();
            speedCounter--;
        }
        UpdateScreen();
    }
}


/*! Responsável pela lógica principal do jogo. Le a entrada de dados do teclado e
 * joystick e toma decisões baseados nessas informações e o estado atual do jogo.
 */
void CGKernel::UpdateLogic()
{
    if (key[KEY_ESC])
        gameOver = true;


    if (key[KEY_UP]    || joy[0].stick[0].axis[1].d1)
		heroi->MoveUp();
    if (key[KEY_DOWN]  || joy[0].stick[0].axis[1].d2)
		heroi->MoveDown();
    if (key[KEY_LEFT]  || joy[0].stick[0].axis[0].d1)
		heroi->MoveLeft();
    if (key[KEY_RIGHT] || joy[0].stick[0].axis[0].d2)
		heroi->MoveRight();
}

void CGKernel::UpdateScreen()
{
    clear_to_color(activePage, 0);
    alfont_textout_centre_aa_ex(activePage, gfont, "Hello World!", SCREEN_W/2, SCREEN_H/2, makecol(255, 255, 255), 0);

    heroi->Draw(activePage);
    show_video_bitmap(activePage);
    activePage = (activePage == page1 ? page2 : page1);
}
