/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "AttackDrawer.hpp"

AttackDrawer::AttackDrawer() : Drawable(),
m_attack(nullptr), m_drawHitboxes(false)
{

}

void AttackDrawer::draw()
{
    //Update matrix
    Drawable::pushMatrix();
    Drawable::updateMatrix();

    m_animDrawer.draw();

    if (m_drawHitboxes)
        drawHitBoxes();

    Drawable::popMatrix();
}

void AttackDrawer::drawHitBoxes()
{
    if (m_attack != nullptr)
    {
        //Show the hitbox for 2*.1s = 200ms
        constexpr float hitBoxSensitivity = .1f;

        float attackTime = m_attack->getCurrentTime();
        Box attackBodyBox;

        const Animation &animation = m_attack->getAnimation();
        animation.getBodyBox(attackBodyBox);

        for (HitBoxDrawer &hitBox : m_hitBoxes)
        {
            float timeDiff = hitBox.hitbox.time - attackTime;
            if (timeDiff < hitBoxSensitivity && -timeDiff < hitBoxSensitivity)
            {
                hitBox.polygon.setPosition(
                    attackBodyBox.left * animation.getXScale(),
                    attackBodyBox.top * animation.getYScale());
                hitBox.polygon.draw();
            }
        }
    }
}

void AttackDrawer::attachTo(const Attack &attack, Texture &texture,
                            bool drawHitboxes)
{
    m_attack = &attack;
    m_animDrawer.attachTo(attack.getAnimation(), texture);

    m_drawHitboxes = drawHitboxes;
    for (HitBox hitBox : attack.getHitBoxes())
    {
        Polygon hitBoxView = Polygon::rectangle(hitBox.box.width,
                                                hitBox.box.height,
                                                Color(0, 0, 0, 0),
                                                Color(225, 0, 0));
        hitBoxView.setOrigin(-hitBox.box.left, -hitBox.box.top);
        hitBoxView.setBorderSize(3.f);
        m_hitBoxes.emplace_back(hitBox, hitBoxView);
    }
}
