// Project Lab - NHTV Igad

#include "UnrealProject.h"

#include "GameListItem.h"
#include "GameList.h"
#include "DefaultGameInstance.h"
#include "SessionManager.h"

UGameListItem::UGameListItem(const FObjectInitializer& init)
	: Super(init)
{
	valid = false;
}

void UGameListItem::NativeConstruct()
{
	Super::NativeConstruct();
	OnGameInfoUpdated();
}

void UGameListItem::SetItem(UGameList* parent, const FOnlineSessionSearchResult& _result)
{
	// Set the sesion result to be displayed in this item
	check(parent);
	m_parent = parent;
	result = &_result;
	valid = result != nullptr;
	if(valid)
	{
		UWorld* world = GetWorld();
		check(world);
		UDefaultGameInstance* inst = Cast<UDefaultGameInstance>(world->GetGameInstance());
		FString nickname = inst->sessionManager->GetPlayerName(*result->Session.OwningUserId);
		// Game Name = Online platform nickname of host
		gameHost = nickname;
		gamePing = result->PingInMs;
		if(!result->Session.SessionSettings.Get(SETTING_MAPNAME, gameMapName))
		{
			GWWARNING(L"Game does not have a map name set");
		}
		gamePlayersMax = result->Session.SessionSettings.NumPublicConnections;
		gamePlayers = gamePlayersMax - result->Session.NumOpenPublicConnections;
	}
	OnGameInfoUpdated();
}

void UGameListItem::Ping()
{
	UDefaultGameInstance* inst = Cast<UDefaultGameInstance>(GetWorld()->GetGameInstance());
	inst->sessionManager->PingResult(*result);
	OnGameInfoUpdated();
}