#include "HyperTwistTraining/HyperTwistCoachDashboardActor.h"

#include "Blueprint/UserWidget.h"
#include "HyperTwistTraining/HyperTwistCoachDashboardWidget.h"

AHyperTwistCoachDashboardActor::AHyperTwistCoachDashboardActor()
{
	PrimaryActorTick.bCanEverTick = false;
}

void AHyperTwistCoachDashboardActor::BeginPlay()
{
	Super::BeginPlay();

	if (bCreateDashboardOnBeginPlay)
	{
		CreateAndShowDashboard();
	}
}

void AHyperTwistCoachDashboardActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	if (bRemoveDashboardOnEndPlay)
	{
		RemoveDashboard();
	}

	Super::EndPlay(EndPlayReason);
}

UHyperTwistCoachDashboardWidget* AHyperTwistCoachDashboardActor::CreateAndShowDashboard()
{
	if (ActiveDashboardWidget != nullptr)
	{
		RefreshDashboard();
		return ActiveDashboardWidget;
	}

	const TSubclassOf<UHyperTwistCoachDashboardWidget> ResolvedWidgetClass = ResolveDashboardWidgetClass();
	if (GetWorld() == nullptr || *ResolvedWidgetClass == nullptr)
	{
		return nullptr;
	}

	ActiveDashboardWidget = CreateWidget<UHyperTwistCoachDashboardWidget>(GetWorld(), ResolvedWidgetClass);
	if (ActiveDashboardWidget == nullptr)
	{
		return nullptr;
	}

	ApplyDashboardDefaults(ActiveDashboardWidget);
	ActiveDashboardWidget->AddToViewport(DashboardZOrder);

	if (bRefreshDashboardOnCreate)
	{
		ActiveDashboardWidget->RefreshCoachDashboardView();
	}

	return ActiveDashboardWidget;
}

void AHyperTwistCoachDashboardActor::RemoveDashboard()
{
	if (ActiveDashboardWidget == nullptr)
	{
		return;
	}

	ActiveDashboardWidget->RemoveFromParent();
	ActiveDashboardWidget = nullptr;
}

void AHyperTwistCoachDashboardActor::RefreshDashboard()
{
	if (ActiveDashboardWidget != nullptr)
	{
		ApplyDashboardDefaults(ActiveDashboardWidget);
		ActiveDashboardWidget->RefreshCoachDashboardView();
	}
}

bool AHyperTwistCoachDashboardActor::HasActiveDashboard() const
{
	return ActiveDashboardWidget != nullptr;
}

TSubclassOf<UHyperTwistCoachDashboardWidget> AHyperTwistCoachDashboardActor::ResolveDashboardWidgetClass() const
{
	if (*DashboardWidgetClass != nullptr)
	{
		return DashboardWidgetClass;
	}

	return UHyperTwistCoachDashboardWidget::StaticClass();
}

void AHyperTwistCoachDashboardActor::ApplyDashboardDefaults(UHyperTwistCoachDashboardWidget* DashboardWidget) const
{
	if (DashboardWidget == nullptr)
	{
		return;
	}

	DashboardWidget->bRefreshOnConstruct = bRefreshDashboardOnCreate;
	DashboardWidget->DefaultUserId = DashboardDefaultUserId;
	DashboardWidget->DefaultSessionId = DashboardDefaultSessionId;
	DashboardWidget->DefaultMode = DashboardDefaultMode;
	DashboardWidget->DefaultCoachMaxCases = DashboardDefaultCoachMaxCases;
}
