#include "simplyEnemy.hpp"
#include "bullet.hpp"
#include "powerup.hpp"
#include "../world.hpp"
#include <resources.h>

namespace game::entity {

SimplyEnemy::SimplyEnemy(Block *root, const vec2f &position, float health) noexcept: Enemy(root, position)
{
    this->body = this->world->CreateBody(this->position, b2_dynamicBody);

    b2PolygonShape shape;
    shape.SetAsBox(0.5, 0.5);

    this->health = health;

    b2FixtureDef fixDef;
    fixDef.filter.categoryBits = TYPE_ENEMY;
    fixDef.filter.maskBits = TYPE_HERO | TYPE_BULLET;
    fixDef.shape = &shape;
    fixDef.density = 1.0f;
    fixDef.userData = this;

    this->body->CreateFixture(&fixDef);

    switch (rand() % 3) {
    case 0:
        resources::atlas.getIcon("crate0.png", this->icon);
        break;
    case 1:
        resources::atlas.getIcon("crate1.png", this->icon);
        break;
    case 2:
        resources::atlas.getIcon("crate2.png", this->icon);
        break;
    }

    this->icon.scale.x = 1 / 16.0;
    this->icon.scale.y = 1 / 16.0;

    this->points = 20;
}

SimplyEnemy::~SimplyEnemy()
{
    if (this->position.x > 0 && this->health <= 0) {
        if (!(rand() % 10)) {
            new PowerUp(this->world, this->position, 3);
        }
    }
}

void SimplyEnemy::OnCollide(Entity *entity)
{
    Bullet *bullet = dynamic_cast<Bullet*>(entity);

    if (bullet) {
        this->health -= bullet->damage;

        if (this->health <= 0) {
            this->Die();
        }
    }
}

void SimplyEnemy::Update() noexcept
{
    this->body->SetLinearVelocity(b2Vec2(-4, 0));
    this->position.x = this->body->GetPosition().x;
    this->position.y = this->body->GetPosition().y;
}

void SimplyEnemy::Render() noexcept
{
    this->icon.draw(this->position);
}

}

