// Gravity Stomp Copyright Kevin Poretti

#include "Player/GSPlayerState.h"

// GS includes
#include "Character/GSCharacter.h"

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

AGSPlayerState::AGSPlayerState()
{
    TeamNum = 0;
    NumKills = 0;
    NumDeaths = 0;
}


void AGSPlayerState::SetTeamNum(int32 InTeamNum)
{
    TeamNum = InTeamNum;
    UpdateTeamColor();
}


void AGSPlayerState::UpdateTeamColor()
{
    AGSCharacter* Char = GetPawn<AGSCharacter>();
    if(Char)
    {
        Char->ChangeTeamColor(false);
    }

    /*
    AGSPlayerState* LocalPS = GetWorld()->GetFirstPlayerController()->GetPlayerState<AGSPlayerState>();
    // if this player state belongs to us then we need to update all other characters
    // rendering of team will essentially flip (all enemies are now rendered as friendly and vice versa)
    if((GetPlayerController() && (GetNetMode() == ENetMode::NM_Client)) || ((GetPlayerController() == GetWorld()->GetFirstPlayerController()) && (GetNetMode() == ENetMode::NM_ListenServer)))
    {
        for(int32 PSIdx = 0; PSIdx < UGameplayStatics::GetNumPlayerStates(GetWorld()); ++PSIdx)
        {
            AGSPlayerState* CurrPS = Cast<AGSPlayerState>(UGameplayStatics::GetPlayerState(GetWorld(), PSIdx));
            if(CurrPS != LocalPS) // only update team colors for remote characters
            {
                AGSCharacter* CurrChar = CurrPS->GetPawn<AGSCharacter>();
                if(CurrChar && CurrPS && LocalPS)
                {
                    CurrChar->ChangeTeamColor(IsPlayerFriendly(CurrPS));
                }
            }
        }
    }
    else // this PS represents a remote player so we just need to switch how we are rendered to the local player
    {
        AGSCharacter* Char = GetPawn<AGSCharacter>();
        if(Char && LocalPS)
        {
            
        }
    }
    */
}


void AGSPlayerState::OnRep_TeamNum()
{
    UE_LOG(LogTemp, Warning, TEXT("%s is on team %d"), *GetPlayerName(), TeamNum);

    UpdateTeamColor();
}


bool AGSPlayerState::IsPlayerFriendly(const AGSPlayerState* PS) const
{
    return TeamNum == PS->GetTeamNum();
}


void AGSPlayerState::Reset()
{
    NumKills = 0;
    NumDeaths = 0;
}


void AGSPlayerState::ClientInitialize(AController* InController)
{
    Super::ClientInitialize(InController);

    UpdateTeamColor();
}


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

	DOREPLIFETIME(AGSPlayerState, NumKills);
    DOREPLIFETIME(AGSPlayerState, NumDeaths);
    DOREPLIFETIME(AGSPlayerState, TeamNum);
}