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

Sprite::Sprite() : Drawable(), m_texture(nullptr)
{
    setSubRect(Box(0.f, 0.f, 1.f, 1.f));
}

Sprite::Sprite(Texture &texture, const Box &subRect) :
Drawable(), m_texture(&texture)
{
    setSubRect(subRect);
}

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

    if (m_texture != nullptr)
        m_texture->draw(m_x1, m_y1, m_x2, m_y2);

    Drawable::popMatrix();
}

void Sprite::setTexture(Texture &texture)
{
    m_texture = &texture;
}

void Sprite::setSubRect(const Box &subRect)
{
    m_subRect = subRect;

    m_x1 = static_cast<GLfloat>(m_subRect.left);
    m_y1 = static_cast<GLfloat>(m_subRect.top);
    m_x2 = static_cast<GLfloat>(m_subRect.left + m_subRect.width);
    m_y2 = static_cast<GLfloat>(m_subRect.top + m_subRect.height);
}

float Sprite::getWidth() const
{
    if (m_texture != nullptr)
        return m_subRect.width * static_cast<float>(m_texture->getWidth());

    return 0.f;
}

float Sprite::getHeight() const
{
    if (m_texture != nullptr)
        return m_subRect.height * static_cast<float>(m_texture->getHeight());

    return 0.f;
}
