/*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 "EventLogger.hpp"
#include "Engines/Resources/FontManager.hpp"

#include "Tools/ScaledPixel.hpp"

EventLogger::EventLogger(FontManager &fontManager, float viewWidth) :
Drawable(), m_font(&(fontManager.getDefault(ScaledPixel{viewWidth}(16)))),
m_viewWidth(viewWidth)
{

}

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

    for (EventEntry &entry : m_eventEntries)
        entry.text.draw();

    Drawable::popMatrix();
}

void EventLogger::update()
{
    while (!m_eventEntries.empty() && Timer::getTime() -
            m_eventEntries.back().time > std::chrono::seconds(10))
        m_eventEntries.pop_back();
}

void EventLogger::clear()
{
    m_eventEntries.clear();
}

void EventLogger::push(const std::string &event)
{
    constexpr std::size_t eventsLimit = 5;
    if (m_eventEntries.size() == eventsLimit)
        m_eventEntries.pop_back();

    if (!m_eventEntries.empty())
        m_eventEntries.front().text.setColor(Color(255, 255, 255, 200),
                                            Color(0, 0, 0, 100));
    m_eventEntries.emplace_front();
    m_eventEntries.front().text.setFont((*m_font));
    m_eventEntries.front().text.setText(event);
    m_eventEntries.front().text.setColor(Color(255, 255, 255),
                                        Color(0, 0, 0, 200));
    updatePositions();
}

void EventLogger::updatePositions()
{
    const float spacing = ScaledPixel{m_viewWidth}(18.f);

    float position = 0.f;
    for (EventEntry &entry : m_eventEntries)
    {
        entry.text.setYPosition(position);
        position += spacing;
    }
}
