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

#include "Tools/I18n.hpp" ///< _ macro for i18n

////////////////
///FpsCounter///
////////////////
FpsCounter::FpsCounter(Font &font) :
Drawable(), m_time(Timer::getTime()), m_ticks(0)
{
    m_text.setFont(font);
    m_text.setColor(Color(255, 255, 255), Color(0, 0, 0, 200));
}

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

    m_text.draw();

    Drawable::popMatrix();
}

void FpsCounter::tick()
{
    m_ticks++;

    const Timer::duration_float_ms elapsedTime(Timer::getTime() - m_time);
    if (elapsedTime >= Timer::duration_float_ms(250.f))
    {
        const float fps = static_cast<float>(m_ticks) / elapsedTime.count();
        m_text.setText(_f(FpsCounterValue,
                          std::make_pair("fps",
                                         static_cast<int>(fps * 1000.f))));
        m_time = Timer::getTime();
        m_ticks = 0;
    }
}

void FpsCounter::reset()
{
    m_text.setText({});
    m_time = Timer::getTime();
    m_ticks = 0;
}

////////////////////////
///OptionalFpsCounter///
////////////////////////
OptionalFpsCounter::OptionalFpsCounter(Font *font) :
m_counter((font != nullptr) ? new FpsCounter((*font)) : nullptr)
{

}

OptionalFpsCounter::~OptionalFpsCounter()
{
    if (m_counter != nullptr)
        delete m_counter;
}

void OptionalFpsCounter::draw()
{
    if (m_counter != nullptr)
        m_counter->draw();
}

void OptionalFpsCounter::tick()
{
    if (m_counter != nullptr)
        m_counter->tick();
}

void OptionalFpsCounter::reset()
{
    if (m_counter != nullptr)
        m_counter->reset();
}

void OptionalFpsCounter::setPosition(float x, float y)
{
    if (m_counter != nullptr)
        m_counter->setPosition(x, y);
}
