//
// Created by Dan Crosby on 11/29/20.
//

#include "PlayerUtils.hpp"

namespace shardok {

auto PlayerIsDefender(const GameState *gameState, int playerId) -> bool {
    const auto playerInfo = std::find_if(
            std::begin(*gameState->player_infos()),
            std::end(*gameState->player_infos()),
            [playerId](const auto *pi) { return pi->player_id() == playerId; });

    if (playerInfo == std::end(*gameState->player_infos())) return false;
    return playerInfo->is_defender();
}

auto NextPlayerId(const GameState *gameState, const PlayerId pid, const bool allowUncontrolled)
        -> PlayerId {
    if (pid == UNCONTROLLED_PLAYER_ID) return 0;

    PlayerId nextPid = UNCONTROLLED_PLAYER_ID;

    for (const auto &pi : *gameState->player_infos()) {
        if (pi->player_id() > pid && pi->player_id() < nextPid) { nextPid = pi->player_id(); }
    }

    if (nextPid == UNCONTROLLED_PLAYER_ID && !allowUncontrolled) return 0;
    return nextPid;
}

auto AlliedPids(const GameState *gameState, int playerId) -> vector<PlayerId> {
    if (gameState->player_infos() == nullptr) return {};
    const auto &pi = std::find_if(
            std::begin(*gameState->player_infos()),
            std::end(*gameState->player_infos()),
            [playerId](const PlayerInfoFb *pi) { return pi->player_id() == playerId; });

    if (pi == std::end(*gameState->player_infos())) { return std::vector<PlayerId>{}; }
    vector<PlayerId> allyPids{};

    if (pi->allies()) {
        for (const auto &ally : *pi->allies()) { allyPids.push_back(ally->player_id()); }
    }
    return allyPids;
}

}  // namespace shardok
