/*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 "LanguageFlag.hpp"
#include "Engines/Resources/TextureManager.hpp"
#include "Graphics/Resources/Texture.hpp"
#include "Graphics/Drawable/Sprite.hpp"

#include <algorithm>
#include <cstddef>

namespace
{
    namespace Metrics
    {
        constexpr float imageWidth = 256.f, imageHeight = 128.f;
        constexpr float flagWidth = 64.f, flagHeight = 40.f, flagGap = 4.f;
        constexpr std::size_t cols = 3;
    }
}

LanguageFlag::LanguageFlag(TextureManager &textureManager,
                           const std::vector<std::string> &localeCodes) :
m_flagsTexture(&(textureManager.getTexture("gfx/flags/flags.png"))),
m_localeCodes(localeCodes)
{

}

Sprite LanguageFlag::getFlagSprite(const std::string &localeCode) const
{
    const std::vector<std::string>::const_iterator it =
        std::find(m_localeCodes.begin(), m_localeCodes.end(), localeCode);

    if (it == m_localeCodes.end())
        return Sprite();

    const std::size_t flagIndex =
        static_cast<std::size_t>(std::distance(m_localeCodes.begin(), it));
    const float colIx = static_cast<float>(flagIndex / Metrics::cols);
    const float rowIx = static_cast<float>(flagIndex % Metrics::cols);

    return Sprite((*m_flagsTexture), Box(
        rowIx * (Metrics::flagWidth + Metrics::flagGap) / Metrics::imageWidth,
        colIx * (Metrics::flagHeight + Metrics::flagGap) / Metrics::imageHeight,
        Metrics::flagWidth / Metrics::imageWidth,
        Metrics::flagHeight / Metrics::imageHeight
    ));
}
