#include "game/bola.hpp"

#include <stdlib.h>

#include "core/jgame.hpp"

Bola::Bola(JD8_Surface gfx, Prota* sam)
    : Sprite(gfx) {
    this->sam = sam;

    this->entitat = (Entitat*)malloc(sizeof(Entitat));
    // Frames
    this->entitat->num_frames = 2;
    this->entitat->frames = (Frame*)malloc(this->entitat->num_frames * sizeof(Frame));
    this->entitat->frames[0].w = 15;
    this->entitat->frames[0].h = 15;
    this->entitat->frames[0].x = 30;
    this->entitat->frames[0].y = 155;
    this->entitat->frames[1].w = 15;
    this->entitat->frames[1].h = 15;
    this->entitat->frames[1].x = 45;
    this->entitat->frames[1].y = 155;

    // Animacions
    this->entitat->num_animacions = 1;
    this->entitat->animacions = (Animacio*)malloc(this->entitat->num_animacions * sizeof(Animacio));
    this->entitat->animacions[0].num_frames = 2;
    this->entitat->animacions[0].frames = (Uint8*)malloc(2);
    this->entitat->animacions[0].frames[0] = 0;
    this->entitat->animacions[0].frames[1] = 1;

    this->cur_frame = 0;
    this->o = 0;
    this->cycles_per_frame = 4;
    this->x = 20;
    this->y = 100;
    this->contador = 0;
}

void Bola::draw() {
    if (this->contador == 0) Sprite::draw();
}

void Bola::update() {
    if (this->contador == 0) {
        // Augmentem la x
        this->x++;
        if (this->x == 280) this->contador = 200;

        // Augmentem el frame
        if (JG_GetCycleCounter() % this->cycles_per_frame == 0) {
            this->cur_frame++;
            if (this->cur_frame == this->entitat->animacions[this->o].num_frames) this->cur_frame = 0;
        }

        // Comprovem si ha tocat a Sam
        if (this->x > (this->sam->x - 7) && this->x < (this->sam->x + 7) && this->y > (this->sam->y - 7) && this->y < (this->sam->y + 7)) {
            this->contador = 200;
            info::vida--;
            if (info::vida == 0) this->sam->o = 5;
        }
    } else {
        this->contador--;
        if (this->contador == 0) this->x = 20;
    }
}
