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


#include "TimeOfDayActor.h"

#include "AsyncMessageSystemBase.h"
#include "AsyncMessageWorldSubsystem.h"
#include "DaySequenceActor.h"
#include "Components/VolumetricCloudComponent.h"
#include "Faye/System/FayeGameplayTags.h"
#include "Kismet/GameplayStatics.h"

ATimeOfDayActor::ATimeOfDayActor(const FObjectInitializer& Init)
: Super(Init)
{
	PrimaryActorTick.bCanEverTick = true;
	VolumetricCloudComponent->SetVisibility(false);
}

void ATimeOfDayActor::BeginPlay()
{
	Super::BeginPlay();
	TimeDef.AddTime((24 + 8) * HOURS_TO_SECONDS);
}

void ATimeOfDayActor::AddTime(float Seconds)
{
	AccumulatedSeconds += (Seconds * RealTimeSpeed);
	if (AccumulatedSeconds >= 1.f)
	{
		int32 AccSecRounded = static_cast<int32>(AccumulatedSeconds);
		TimeDef.AddTime(AccSecRounded);
		AccumulatedSeconds -= static_cast<float>(AccSecRounded);
	}
	SetTimeOfDay(TimeDef.GetTimeOfDayInHours());
	
	FTimeChangedPayload Payload;
	Payload.SecondsPassed = AccumulatedSeconds;
	OnTimeChanged.Broadcast(Payload);
	if (TSharedPtr<FAsyncMessageSystemBase> Sys = UAsyncMessageWorldSubsystem::GetSharedMessageSystem(GetWorld()))
	{
		Sys->QueueMessageForBroadcast(FAsyncMessageId(::Event::TimeOfDay::TimePassed), FConstStructView::Make(Payload));
	}
}

void ATimeOfDayActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (bTimeActive && GetWorld() && GetWorld()->IsGameWorld())
	{
		AddTime(DeltaTime);
	}
}
