#include "UIServerCard_Base.h"

#include "ZMMO.h"
#include "CommonTextBlock.h"
#include "Components/Border.h"
#include "Components/ProgressBar.h"
#include "UI/Widgets/UIButton_Base.h"

void UUIServerCard_Base::NativePreConstruct()
{
	Super::NativePreConstruct();
	// TODO(ui-system): reativar quando UUIButton_Base voltar a ter RefreshUIStyle.
	// if (Btn_Enter)
	// {
	// 	Btn_Enter->RefreshUIStyle();
	// }
}

void UUIServerCard_Base::NativeConstruct()
{
	Super::NativeConstruct();
	if (Btn_Enter && !bBound)
	{
		Btn_Enter->OnClicked().AddUObject(this, &UUIServerCard_Base::HandleEnterClicked);
		bBound = true;
	}
	// TODO(ui-system): reativar quando UUIButton_Base voltar a ter RefreshUIStyle.
	// if (Btn_Enter)
	// {
	// 	Btn_Enter->RefreshUIStyle();
	// }
}

void UUIServerCard_Base::NativeDestruct()
{
	if (Btn_Enter && bBound)
	{
		Btn_Enter->OnClicked().RemoveAll(this);
		bBound = false;
	}
	Super::NativeDestruct();
}

void UUIServerCard_Base::SetFromEntry(const FZMMOWorldEntry& InEntry)
{
	Entry = InEntry;

	if (Text_Name)
	{
		Text_Name->SetText(FText::FromString(Entry.WorldName));
	}
	if (Text_Pop)
	{
		Text_Pop->SetText(FText::FromString(FString::Printf(TEXT("%d/%d"), Entry.Population, Entry.Capacity)));
	}
	if (Text_Status)
	{
		Text_Status->SetText(FormatStatus(Entry.State));
	}
	if (Bar_Pop)
	{
		const float Ratio = (Entry.Capacity > 0)
			? FMath::Clamp(static_cast<float>(Entry.Population) / static_cast<float>(Entry.Capacity), 0.f, 1.f)
			: 0.f;
		Bar_Pop->SetPercent(Ratio);
	}

	// Botao "Selecionar" sempre habilitado — mesmo com world offline,
	// o usuario pode entrar no Lobby pra ver a lista de personagens, criar/
	// deletar. O gate de "entrar no mundo" fica no proprio Lobby (botao
	// "Entrar no Servidor"), que checa World.State antes do handoff.
	// TODO(ui-system): reativar quando UUIButton_Base voltar a ter RefreshUIStyle.
	// if (Btn_Enter)
	// {
	// 	Btn_Enter->RefreshUIStyle();
	// }
}

void UUIServerCard_Base::HandleEnterClicked()
{
	OnCardPressed.Broadcast(Entry.WorldId, Entry.State);
}

FText UUIServerCard_Base::FormatStatus_Implementation(uint8 State) const
{
	switch (State)
	{
		case 1: return NSLOCTEXT("ZMMO.ServerSelect", "StatusOnline",      "Online");
		case 2: return NSLOCTEXT("ZMMO.ServerSelect", "StatusMaintenance", "Manutencao");
		case 0:
		default: return NSLOCTEXT("ZMMO.ServerSelect", "StatusOffline",   "Offline");
	}
}
