/*Copyright (C) 2010-2012 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 "Text.hpp"

Text::Text() : Drawable()
{
    
}

Text::Text(const std::string &text, Font &font) :
Drawable(), m_font(&font), m_text(text)
{
    updateSize();
}

void Text::draw()
{
    if (m_font != NULL)
    {
        //Update matrix
        Drawable::pushMatrix();
        Drawable::updateMatrix();
        
        glColor4ub(m_color.red, m_color.green, m_color.blue, m_color.alpha);
        glTranslatef(0, m_height, 0);
        
        for (unsigned int i = 0; i < m_text.size(); i++)
        {
            const Glyph *glyph = m_font->getGlyph(m_text[i]);
            
            glyph->draw();
            glTranslatef(glyph->getAdvance().x / 64, -glyph->getAdvance().y / 64, 0);
        }
        
        glColor4ub(255, 255, 255, 255); //Restore default color
        
        Drawable::popMatrix();
    }
}

void Text::setFont(Font &font)
{
    m_font = &font;
    updateSize();
}

const Font &Text::getFont() const
{
    return *m_font;
}

void Text::setText(const std::string &text)
{
    m_text = text;
    updateSize();
}

const std::string &Text::getText() const
{
    return m_text;
}

void Text::setColor(const Color &color)
{
    m_color = color;
}

const Color &Text::getColor() const
{
    return m_color;
}

float Text::getWidth() const
{
    return m_width;
}

float Text::getHeight() const
{
    return m_height;
}

void Text::updateSize()
{
    if (m_font != NULL)
    {
        float width = 0, top = 0, bottom = 0;
        for (unsigned int i = 0; i < m_text.size(); i++)
        {
            const Glyph *glyph = m_font->getGlyph(m_text[i]);
            
            //Width
            if (i < m_text.size() - 1) width += glyph->getAdvance().x / 64;
            else width += glyph->getWidth();
            
            //Height
            if (-glyph->getTopLeft().y < top)
                top = -glyph->getTopLeft().y;
            
            if (top + glyph->getHeight() > bottom)
                bottom = top + glyph->getHeight();
        }
        
        m_width = width;
        m_height = bottom - top;
    }
}
