#include "game/engendro.hpp"

#include <stdlib.h>

#include "core/jail/jgame.hpp"

Engendro::Engendro(JD8_Surface gfx, Uint16 x, Uint16 y)
    : Sprite(gfx) {
    this->entitat = (Entitat*)malloc(sizeof(Entitat));
    // Frames
    this->entitat->num_frames = 4;
    this->entitat->frames = (Frame*)malloc(this->entitat->num_frames * sizeof(Frame));

    Uint8 frame = 0;
    for (int y = 50; y <= 65; y += 15) {
        for (int x = 225; x <= 240; x += 15) {
            this->entitat->frames[frame].w = 15;
            this->entitat->frames[frame].h = 15;
            this->entitat->frames[frame].x = x;
            this->entitat->frames[frame].y = y;
            frame++;
        }
    }

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

    this->cur_frame = 0;
    this->vida = 18;
    this->x = x;
    this->y = y;
    this->o = 0;
    this->cycles_per_frame = 30;
}

void Engendro::draw() {
    Sprite::draw();
}

bool Engendro::update() {
    bool mort = false;

    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;
        this->vida--;
    }

    if (vida == 0) mort = true;

    return mort;
}
