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


#include "PauseMenuWidget.h"

#include "Components/Button.h"
#include "FpsPlayerController.h"

void UPauseMenuWidget::NativeConstruct()
{
	Super::NativeConstruct();

	if (ResumeButton)
	{
		ResumeButton->OnClicked.AddDynamic(this, &UPauseMenuWidget::HandleResumeClicked);
	}

	if (QuitToMenuButton)
	{
		QuitToMenuButton->OnClicked.AddDynamic(this, &UPauseMenuWidget::HandleQuitToMenuClicked);
	}

	if (SettingsButton)
	{
		SettingsButton->OnClicked.AddDynamic(this, &UPauseMenuWidget::HandleSettingsClicked);
	}

	if (InviteButton)
	{
		InviteButton->OnClicked.AddDynamic(this, &UPauseMenuWidget::HandleInviteClicked);

		// Evalue une seule fois : le menu de pause n'est construit qu'a la
		// premiere ouverture, donc bien apres que la session ait reussi ou
		// echoue. Rien ne peut plus changer cet etat en cours de partie.
		const AFpsPlayerController* Controller = GetOwningPlayer<AFpsPlayerController>();
		InviteButton->SetIsEnabled(Controller && Controller->CanInviteFriends());
	}
}

void UPauseMenuWidget::NativeDestruct()
{
	if (ResumeButton)
	{
		ResumeButton->OnClicked.RemoveDynamic(this, &UPauseMenuWidget::HandleResumeClicked);
	}

	if (SettingsButton)
	{
		SettingsButton->OnClicked.RemoveDynamic(this, &UPauseMenuWidget::HandleSettingsClicked);
	}

	if (QuitToMenuButton)
	{
		QuitToMenuButton->OnClicked.RemoveDynamic(this, &UPauseMenuWidget::HandleQuitToMenuClicked);
	}

	if (InviteButton)
	{
		InviteButton->OnClicked.RemoveDynamic(this, &UPauseMenuWidget::HandleInviteClicked);
	}

	Super::NativeDestruct();
}

void UPauseMenuWidget::HandleSettingsClicked()
{
	if (AFpsPlayerController* Controller = GetOwningPlayer<AFpsPlayerController>())
	{
		Controller->OpenSettings();
	}
}

void UPauseMenuWidget::HandleResumeClicked()
{
	if (AFpsPlayerController* Controller = GetOwningPlayer<AFpsPlayerController>())
	{
		Controller->ResumeGame();
	}
}

void UPauseMenuWidget::HandleQuitToMenuClicked()
{
	if (AFpsPlayerController* Controller = GetOwningPlayer<AFpsPlayerController>())
	{
		Controller->RequestQuitToMainMenu();
	}
}

void UPauseMenuWidget::HandleInviteClicked()
{
	if (AFpsPlayerController* Controller = GetOwningPlayer<AFpsPlayerController>())
	{
		Controller->ShowInviteFriends();
	}
}
