#include "entity.h"
#include "debuggers.h"

namespace pabloader {
Entity::Entity(Debuggers* game, olc::Sprite* s)
    : sprite(s)
    , pos(0, 0)
    , vel(0, 0)
    , size(s->width / 4, s->height / 4)
{
    Entity::game = game;
}

void Entity::Update(float dt)
{
    pos += vel * dt;
    vel.y += game->gravity * dt;

    rotation += rotationSpeed * dt;

    transform.Reset();
    transform.Rotate(rotation);
    transform.Translate(pos.x, pos.y);
}

bool Entity::Collides(Entity* entity)
{
    bool collidesX = (pos.x - size.x / 2 < entity->pos.x + entity->size.x / 2) && (entity->pos.x - entity->size.x / 2 < pos.x + size.x / 2);
    bool collidesY = (pos.y - size.y / 2 < entity->pos.y + entity->size.y / 2) && (entity->pos.y - entity->size.y / 2 < pos.y + size.y / 2);
    return collidesX && collidesY;
}

void Entity::Draw()
{
#ifdef _DEBUG
    if (game->debug) {
        game->DrawRect(pos.x - size.x / 2, pos.y - size.y / 2, size.x, size.y, DEBUG_COLOR);
    }
#endif
    game->SetPixelMode(olc::Pixel::MASK);
    olc::GFX2D::DrawPartialSprite(sprite, tile.x * size.x, tile.y * size.y, size.x, size.y, transform, true);
    game->SetPixelMode(olc::Pixel::NORMAL);
}

bool Entity::IsActive()
{
    return pos.y - size.y / 2 < game->GameScreenHeight();
}
bool Entity::IsInScreen()
{
    return pos.x > -size.x / 2 && pos.y > -size.y
        && pos.x < game->ScreenWidth() + size.x / 2
        && pos.y < game->ScreenHeight() + size.y / 2;
}

bool Entity::IsAlive()
{
    return alive;
}

void Entity::ResetPosition()
{
    pos.x = game->GetRandom(size.x, game->ScreenWidth() - size.x);
    pos.y = game->GetRandom(-20, -game->ScreenHeight());
    vel.x = 0;
    vel.y = 0;
    tile.x = game->GetRandom<int>(0, tileDim.x);
    tile.y = game->GetRandom<int>(0, tileDim.y);
    rotationSpeed = game->GetRandom(-3.14f, 3.14f);
    alive = true;
}

void Entity::Kill()
{
    pos.y = game->ScreenHeight() + 100;
    alive = false;
}
}