#include <ChatCommand/ChatCommand.hpp>
#include <Log/Log.hpp>
#include <UserPermission/UserPermission.hpp>

void ChatCommand::require(UserPermission perm)
{
    requiredPermissions.push_back(perm);
}

bool ChatCommand::isAllowedFor(Player &player)
{
    for (const auto &perm : requiredPermissions)
    {
        if (!player.hasPermission(perm))
        {
            return false;
        }
    }

    return true;
}

void ChatCommand::showHelp(Player &player, std::string commandName, glm::vec3 color)
{
    for (const auto &variant : variants)
    {
        player.writeChat(formatString("  /$+ $+", commandName, variant.syntax), color);
    }
}

void ChatCommand::execute(Player &player, const std::vector<std::string> &args)
{
    for (const auto &perm : requiredPermissions)
    {
        if (!isAllowedFor(player))
        {
            player.writeChat("You do not have permission to use this command.", Color::error);
            Log::error(
                formatString(
                    "[$+]: /$+: Permission '$+' not granted.",
                    player.getName(),
                    args[0],
                    userPermNameByEnum[perm]
                )
            );

            return;
        }
    }

    for (const auto &variant : variants)
    {
        if (variant.execute(player, args))
        {
            return;
        }
    }

    player.writeChat("SYNTAX:", Color::error);
    showHelp(player, args[0], Color::error);
    Log::error(formatString("[$+] Invalid syntax for '$+'", player.getName(), args[0]));
}