// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "SplashScreenItem.h"
#include "MediaTexture.h"

USplashScreenItem::USplashScreenItem(const FObjectInitializer& init)
	: Super(init)
{
	duration = 2.0f;
	fadeDuration = 0.5f;
	m_lifetime = 0.0f;
	fadeEnabled = true;
}

void USplashScreenItem::NativeConstruct()
{
	if(duration <= 0.0f)
	{
		GWWARNING(L"Splash screen duration is zero! " + GetName());
		duration = 1.0f;
	}
	if(fadeDuration * 2.0f > duration)
	{
		GWWARNING(L"Splash screen fade time is greater than duration! " + GetName());
		fadeDuration = duration * 0.25f;
	}

	m_started = false;
	Super::NativeConstruct();
}
void USplashScreenItem::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
	if(m_started)
		m_lifetime += InDeltaTime;
	Super::NativeTick(MyGeometry, InDeltaTime);
}

void USplashScreenItem::OnStarted_Implementation()
{

}
void USplashScreenItem::OnEnd_Implementation()
{

}
void USplashScreenItem::Skip()
{
	if((m_lifetime + fadeDuration) < duration)
	{
		m_lifetime = duration - fadeDuration;
	}
}

void USplashScreenItem::Start()
{
	if(!m_started)
	{
		m_started = true;
		m_lifetime = 0.0f;
		OnStarted();
	}
}
void USplashScreenItem::End()
{
	if(m_started)
	{
		OnEnd();
		m_started = false;
	}
}

FVector2D USplashScreenItem::GetMediaSize(UMediaTexture* mediaTexture) const
{
	if(!mediaTexture)
		return FVector2D();
	return FVector2D(mediaTexture->GetSurfaceWidth(), mediaTexture->GetSurfaceHeight());
}

float USplashScreenItem::GetFade() const
{
	float base = GetFadeOut();
	if(m_lifetime < fadeDuration)
	{
		base *= m_lifetime / fadeDuration;
	}
	return base;
}
float USplashScreenItem::GetFadeOut() const
{
	if((duration - m_lifetime) < fadeDuration)
	{
		return FMath::Min((duration - m_lifetime) / fadeDuration, 1.0f);
	}
	else
	{
		return 1.0f;
	}
}

float USplashScreenItem::GetRate() const
{
	return FMath::Clamp(m_lifetime / duration, 0.0f, 1.0f);
}
