// Gravity Stomp Copyright Kevin Poretti

#include "GameModes/GSGameState.h"

// UE includes
#include "Net/UnrealNetwork.h"

void AGSGameState::SetNumTeams(int32 InNumTeams)
{
    NumTeams = InNumTeams;

    // Grow team score array if num teams is greater than current capacity
    if(TeamScores.Num() < NumTeams)
    {
        TeamScores.AddZeroed(NumTeams - TeamScores.Num());
    }
}


int32 AGSGameState::GiveTeamPoint(int32 InTeamIdx)
{
    if(InTeamIdx < 0 || InTeamIdx >= TeamScores.Num())
    {
        UE_LOG(LogTemp, Error, TEXT("Tried to give team %d a point but the team index is out of range"), InTeamIdx);
        return -1;
    }

    TeamScores[InTeamIdx]++;
    OnTeamScoresUpdated.Broadcast(TeamScores);
    return TeamScores[InTeamIdx];
}


void AGSGameState::ResetTeamScores()
{
    for(int32 TeamIdx = 0; TeamIdx < TeamScores.Num(); TeamIdx++)\
    {
        TeamScores[TeamIdx] = 0;
    }

    OnTeamScoresUpdated.Broadcast(TeamScores);
}


int32 AGSGameState::GetWinningTeam()
{
    int32 WinningTeamIdx = 0;
    int32 WinningTeamScore = 0;
    for(int32 TeamIdx = 0; TeamIdx < TeamScores.Num(); TeamIdx++)\
    {
        if(TeamScores[TeamIdx] > WinningTeamScore)
        {
            WinningTeamIdx = TeamIdx;
            WinningTeamScore = TeamScores[TeamIdx];
        }
    }

    return WinningTeamIdx;
}


void AGSGameState::SetRemainingTime(float InRemainingTime)
{
    RemainingTime = InRemainingTime;

    OnRemainingTimeUpdated.Broadcast(RemainingTime);
}

void AGSGameState::OnRep_MatchState()
{
    Super::OnRep_MatchState();

    OnMatchStateUpdated.Broadcast(GetMatchState());
}


void AGSGameState::OnRep_TeamScores()
{
    OnTeamScoresUpdated.Broadcast(TeamScores);
}


void AGSGameState::OnRep_RemainingTime()
{
    OnRemainingTimeUpdated.Broadcast(RemainingTime);
}


void AGSGameState::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);

    DOREPLIFETIME(AGSGameState, NumTeams);
    DOREPLIFETIME(AGSGameState, TeamScores);
    DOREPLIFETIME(AGSGameState, RemainingTime);
}