// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "SplashScreen.h"
#include "SplashScreenItem.h"
#include "DefaultGameInstance.h"
#include "SessionManager.h"

USplashScreen::USplashScreen(const FObjectInitializer& init)
	: Super(init)
{
}

void USplashScreen::NativeConstruct()
{
	m_currentItem = -1;
	Super::NativeConstruct();
}
void USplashScreen::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
	Super::NativeTick(MyGeometry, InDeltaTime);
	if(m_currentItem == -1)
		return;

	if(m_currentItem >= m_activeScreens.Num())
	{
		OnEnd();
		// Send done event
		onDone.Broadcast();
		m_currentItem = -1;
	}
	else
	{
		m_switcher->SetActiveWidget(m_activeScreens[m_currentItem]);
		if(m_activeScreens[m_currentItem]->GetRate() >= 1.0f)
		{
			m_activeScreens[m_currentItem]->End();
			m_currentItem++;
			if(m_currentItem < m_activeScreens.Num())
			{
				m_activeScreens[m_currentItem]->Start();
			}
		}
	}
}

void USplashScreen::NativeOnMenuAction(EMenuActionBinding binding)
{
	if(binding == EMenuActionBinding::Start)
	{
		if(m_currentItem >= 0 && m_currentItem < m_activeScreens.Num())
		{
			m_activeScreens[m_currentItem]->Skip();
		}
	}
}

void USplashScreen::OnEnd_Implementation()
{

}

void USplashScreen::Init(UWidgetSwitcher* witcher)
{
	m_switcher = witcher;
	m_currentItem = 0;

	for(int32 i = 0; i < splashItems.Num(); i++)
	{
		USplashScreenItem* item = CreateWidget<USplashScreenItem>(GetWorld(), splashItems[i]);
		m_activeScreens.Add(item);
		m_switcher->AddChild(item);
		if(i == 0)
		{
			item->Start();
			if((i + 1) == splashItems.Num())
				item->fadeEnabled = false;
			m_switcher->SetActiveWidget(item);
		}
	}
}

float USplashScreen::GetFade() const
{
	if(m_currentItem == -1)
		return 0.0f;
	if(m_currentItem >= m_activeScreens.Num())
	{
		return 0.0f;
	}
	if((m_currentItem + 1) == m_activeScreens.Num())
	{
		return m_activeScreens[m_currentItem]->GetFadeOut();
	}
	return 1.0f;
}
