/*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 "Tab.hpp"

Tab::Tab() : Widget(), m_labelFont(NULL), m_horizontalSpace(0)
{
    
}

void Tab::draw()
{
    //Update matrix
    Drawable::pushMatrix();
    Drawable::updateMatrix();
    
    std::vector< std::pair<Text, Widget*> >::iterator it;
    for (it = m_widgetsList.begin(); it != m_widgetsList.end(); it++)
    {
        it->first.draw();
        it->second->draw();
    }
    
    Drawable::popMatrix();
}

void Tab::setLabelFont(Font &font)
{
    m_labelFont = &font;
}

const Font *Tab::getLabelFont() const
{
    return m_labelFont;
}

float Tab::getWidth() const
{
    float width = 0;
    
    std::vector< std::pair<Text, Widget*> >::const_iterator it;
    for (it = m_widgetsList.begin(); it != m_widgetsList.end(); it++)
    {
        Widget *widget = it->second;
        
        if (width < widget->getXPosition() + widget->getWidth())
            width = widget->getXPosition() + widget->getWidth();
    }
    
    return width;
}

float Tab::getHeight() const
{
    if (m_widgetsList.size() > 0)
        return m_widgetsList.back().second->getYPosition() + m_widgetsList.back().second->getHeight();
    
    return 0;
}

bool Tab::addWidget(const std::string &label, Widget &widget, float space)
{
    if (m_labelFont != NULL)
    {
        Text labelText(label, *m_labelFont);
        m_widgetsList.push_back( std::make_pair(labelText, &widget) );
        
        if (labelText.getWidth() + 20 > m_horizontalSpace)
            m_horizontalSpace = labelText.getWidth() + 20;
        
        //Position
        float base = space;
        if (m_widgetsList.size() > 1)
        {
            Widget *previousWidget = m_widgetsList[m_widgetsList.size() - 2].second;
            base = (previousWidget->getYPosition() + previousWidget->getHeight()) + space;
        }
        
        Text &addedLabel = m_widgetsList.back().first;
        Widget *addedWidget = m_widgetsList.back().second;
        
        addedLabel.setYPosition(base + (addedWidget->getHeight() - addedLabel.getHeight()) / 2);
        
        addedWidget->setXPosition(m_horizontalSpace);
        addedWidget->setYPosition(base);
        
        return true;
    }
    
    return false;
}
