// © 2025 Naked People Team. All Rights Reserved.


#include "Mission.h"

#include "MissionGoal.h"

void UMission::Init(ANakedDesireCharacter* PlayerCharacter)
{
	Player = PlayerCharacter;

	for (const auto& Goal : Goals)
	{
		Goal->Init(Player);
		auto Handle = Goal->OnUpdate.AddUObject(this, &UMission::OnGoalUpdated);
		GoalUpdateHandles.Add(Handle);
	}
}

void UMission::OnGoalUpdated(UMissionGoal* MissionGoal)
{
	if (IsCompleted)
	{
		return;
	}

	if (CheckGoals())
	{
		Complete();
	}
}

void UMission::Complete()
{
	IsCompleted = true;
	
	for (const auto& Goal : Goals)
	{
		for (const auto& Handle : GoalUpdateHandles)
		{
			Goal->OnUpdate.Remove(Handle);
		}
	}
		
	OnComplete.Broadcast(this);
}

bool UMission::CheckGoals()
{
	if (IsCompleted)
	{
		return true;
	}

	for (const auto& Goal : Goals)
	{
		if (!Goal->GetIsCompleted() || !Goal->CheckRestrictions())
		{
			return false;
		}
	}
	return true;
}
