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

PlayerWidget::PlayerWidget() : m_barsWidth(0), m_barsHeight(0)
{
    
}

void PlayerWidget::draw()
{
    //Update matrix
    Drawable::pushMatrix();
    Drawable::updateMatrix();
    
    m_name.draw();
    
    m_lifeBar.draw();
    m_lifeText.draw();
    
    Drawable::popMatrix();
}

void PlayerWidget::update()
{
    if (m_player != NULL)
    {
        std::string playerName = m_player->getName();
        
        if (m_name.getText() != playerName)
            m_name.setText(playerName);
        
        float playerHealth = m_player->getHealth();
        
        std::ostringstream healthText;
        healthText << playerHealth;
        
        m_lifeText.setText(healthText.str() + " / 100");
        m_lifeBar.setXScale(playerHealth / 100);
    }
}

void PlayerWidget::init()
{
    const Font &nameFont = m_name.getFont();
    const Font &barsFont = m_lifeText.getFont();
    
    m_barsHeight = (barsFont.getCharSize() / 1.3) + 10;
    m_barsWidth = m_barsHeight * 6;
    
    m_lifeBar = Polygon::rectangle(0, 0, m_barsWidth, m_barsHeight, Color(0, 255, 0, 75));
    m_lifeBar.setYPosition((nameFont.getCharSize() / 1.3) + 5);
    m_lifeBar.enableBorder(false);
    
    m_lifeText.setXPosition(m_lifeBar.getXPosition() + 20);
    m_lifeText.setYPosition(m_lifeBar.getYPosition() + 5);
    m_lifeText.setColor(Color(255, 255, 255, 200));
}

//Get and set methods
void PlayerWidget::setPlayer(Player &player)
{
    m_player = &player;
}

const Player &PlayerWidget::getPlayer() const
{
    return *m_player;
}

void PlayerWidget::setFonts(Font &nameFont, Font &barsFont)
{
    m_name.setFont(nameFont);
    m_lifeText.setFont(barsFont);
    
    init();
}

const Font &PlayerWidget::getNameFont() const
{
    return m_name.getFont();
}

const Font &PlayerWidget::getBarsFont() const
{
    return m_lifeText.getFont();
}

float PlayerWidget::getWidth() const
{
    if (m_barsWidth > m_name.getWidth())
        return m_barsWidth;
    
    return m_name.getWidth();
}

float PlayerWidget::getHeight() const
{
    return m_lifeBar.getYPosition() + m_barsHeight;
}
