// Fill out your copyright notice in the Description page of Project Settings.


#include "DemoUserWidget.h"
#include "Components/TextBlock.h"
#include "EventManager.h"
#include "DemoEvent.h"

UDemoUserWidget::UDemoUserWidget(const FObjectInitializer& ObjectInitializer) :
	UUserWidget(ObjectInitializer)
{
	FPlatformMisc::CreateGuid(GUID);
	callbackFunction.BindWeakLambda(this, [this](const EventPtr& evt) { this->OnDemoEvent(evt); });
}

void UDemoUserWidget::NativePreConstruct()
{
	return Super::NativePreConstruct();
}

void UDemoUserWidget::NativeConstruct()
{
	if (DemoTextBlock != nullptr)
	{
		DemoTextBlock->SetText(FText::FromString("Test"));
	}

	EventManager::getInstance().addListener(callbackFunction, DemoEvent::Identity, Identifier(GUID.ToString()));

	return Super::NativeConstruct();
}

void UDemoUserWidget::NativeDestruct()
{
	EventManager::getInstance().removeListener(Identifier(GUID.ToString()));

	return Super::NativeDestruct();
}

void UDemoUserWidget::OnDemoEvent(const EventPtr& evt)
{
	DemoEvent* demoEvent = (DemoEvent*)(evt.Get());
	if (demoEvent != nullptr && DemoTextBlock != nullptr)
	{
		DemoTextBlock->SetText(FText::FromString(FString::FromInt(demoEvent->getNewValue())));

		if (GEngine)
		{
			GEngine->AddOnScreenDebugMessage(123456, 0.1f, FColor::White, TEXT("This is an Example on-screen debug message."));
		}
	}
}