#include "chaseEnemy.hpp"
#include "bullet.hpp"
#include "../world.hpp"
#include <app.hpp>

namespace game::entity {

ChaseEnemy::ChaseEnemy(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);

    this->velocity = b2Vec2(-4, 0);

    switch (rand() % 2) {
    case 0:
        App::atlas->getIcon("chase0.png", this->icon);
        break;
    case 1:
        App::atlas->getIcon("chase1.png", this->icon);
        break;
    }

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

    this->angle = 0;

    this->points = 40;
}

ChaseEnemy::~ChaseEnemy()
{

}

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

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

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

void ChaseEnemy::Update() noexcept
{
    this->position.x = this->body->GetPosition().x;
    this->position.y = this->body->GetPosition().y;

    if (this->IsOnScreen()) {
        vec2f newVelocity = (this->world->GetPlayerPosition() - this->position).normalize() * 6;
        this->velocity.x = newVelocity.x;
        this->velocity.y = newVelocity.y;

        this->angle = atan2(newVelocity.y, newVelocity.x);
    } else if (this->position.x < 2) {
        this->world->RemoveManagedEntity(this);
    }

    this->body->SetLinearVelocity(this->velocity);

}

void ChaseEnemy::Render() noexcept
{
    this->icon.angle = this->angle;
    this->icon.draw(this->position);
    //render::primitives::Circle(this->position, vec2f{0.5, 0.5}, color::green, 0, 16);
    //render::primitives::Circle(this->position - vec2f{0.4, 0.4}, vec2f{0.3, 0.1}, color::green, 45, 16);
    //render::primitives::Circle(this->position - vec2f{0.4, -0.4}, vec2f{0.3, 0.1}, color::green, -45, 16);
}

}

