/*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 "AnimationDrawer.hpp"
#include "Animation/Animation.hpp"
#include "Graphics/Resources/Texture.hpp"

AnimationDrawer::AnimationDrawer() : Drawable(), m_animation(nullptr),
m_texture(nullptr), m_drawFrameIx(0), m_x1(0.f), m_y1(0.f), m_x2(0.f), m_y2(0.f)
{

}

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

    if (m_texture != nullptr)
    {
        if (m_animation->getCurrentFrame() != m_drawFrameIx)
            computeTextureCoordinates();

        m_texture->draw(m_x1, m_y1, m_x2, m_y2);
    }

    Drawable::popMatrix();
}

void AnimationDrawer::attachTo(const Animation &animation, Texture &texture)
{
    m_animation = &animation;
    m_texture = &texture;

    setScale(animation.getXScale(), animation.getYScale());
    computeTextureCoordinates();
}

void AnimationDrawer::computeTextureCoordinates()
{
    if (m_texture != nullptr && m_animation != nullptr &&
        m_animation->getSourceBox(m_drawBox))
    {
        GLfloat textureWidth = static_cast<GLfloat>(m_texture->getWidth()),
                textureHeight = static_cast<GLfloat>(m_texture->getHeight());

        m_x1 = (textureWidth > 0.f) ? static_cast<GLfloat>(m_drawBox.left) / textureWidth : 0.f;
        m_y1 = (textureHeight > 0.f) ? static_cast<GLfloat>(m_drawBox.top) / textureHeight : 0.f;

        m_x2 = (textureWidth > 0.f) ? static_cast<GLfloat>(m_drawBox.left + m_drawBox.width) / textureWidth : 1.f;
        m_y2 = (textureHeight > 0.f) ? static_cast<GLfloat>(m_drawBox.top + m_drawBox.height) / textureHeight : 1.f;

        m_drawFrameIx = m_animation->getCurrentFrame();
    }
}
