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

#include "Tools/ScaledPixel.hpp"

NameTags::NameTags(const Vector &viewSize, FontManager &fontManager) :
m_viewport(Box(0.f, 0.f, viewSize.x, viewSize.y)),
m_font(&(fontManager.getDefault(ScaledPixel{viewSize.x}(16))))
{

}

void NameTags::draw()
{
    for (PlayerTag &tag : m_tags)
        tag.text.draw();
}

void NameTags::update()
{
    updatePositions();
}

void NameTags::setPlayers(const std::vector<TaggedPlayer> &players)
{
    m_tags.clear();
    m_tags.reserve(players.size());
    for (const TaggedPlayer &player : players)
    {
        m_tags.emplace_back(player);
        m_tags.back().text.setFont((*m_font));
        m_tags.back().text.setText(player.username);
        m_tags.back().text.setColor(Color(220, 220, 220), Color(0, 0, 0, 200));
        m_tags.back().width = m_tags.back().text.getWidth();
    }

    updatePositions();
}

void NameTags::setCameraView(const Box &view)
{
    m_viewport.setSource(view);
    updatePositions();
}

void NameTags::updatePositions()
{
    for (PlayerTag &tag : m_tags)
    {
        const Box &playerBox = tag.tag.player->getBox();
        const Vector projected = m_viewport.project(
            Vector(playerBox.left + playerBox.width / 2.f,
                   playerBox.top -
                        ScaledPixel{m_viewport.getTargetSize().x}(70.f)));

        tag.text.setPosition(projected.x - tag.width / 2.f, projected.y);
    }
}
