// Copyright (c) Microsoft Corporation. 
// Licensed under the MIT license.

#include "SAllowMorphTargetsPerLOD.h"
#include "LODRecipe.h"
#include "SAllowMorphTargetsWidget.h"

#include "Widgets/Input/SCheckBox.h"

void SAllowMorphTargetsPerLOD::Construct(const FArguments& Args, const TSharedRef<SAllowMorphTargetsWidget> Owner)
{
	OwnerWidget = Owner;
	PerLODCheckBoxes = SNew(SHorizontalBox);
	OnPropertyChangedDelegateHandle = FCoreUObjectDelegates::OnObjectPropertyChanged.AddSP(this, &SAllowMorphTargetsPerLOD::OnPropertyChanged);

	ChildSlot
	[
		SNew(SHorizontalBox)
		+ SHorizontalBox::Slot()
		.AutoWidth()
		.Padding(0.0f, 4.0f, 4.0f, 4.0f)
		[
			SNew(STextBlock)
			.Text(FText::FromString(TEXT("Allow Morph Targets:")))
			.Font(FCoreStyle::GetDefaultFontStyle("Bold", 10))
		]
		+ SHorizontalBox::Slot()
		[
			PerLODCheckBoxes.ToSharedRef()
		]
	];

	RefreshPerLODCheckBoxes();
}

SAllowMorphTargetsPerLOD::~SAllowMorphTargetsPerLOD()
{
	FCoreUObjectDelegates::OnObjectPropertyChanged.Remove(OnPropertyChangedDelegateHandle);
	OnPropertyChangedDelegateHandle.Reset();
}

void SAllowMorphTargetsPerLOD::RefreshPerLODCheckBoxes()
{
	ULODRecipe* LODRecipe = OwnerWidget.Pin()->GetLODRecipe();

	PerLODCheckBoxes->ClearChildren();

	const FMargin RightPadding(0.0f, 0.0f, 8.0f, 0.0f);
	int32 NumLODs = OwnerWidget.Pin()->GetLODRecipe()->GetNumLODs();
	for (int32 LODIndex = 1; LODIndex < NumLODs; ++LODIndex)
	{
		FString LODHeader = FString::Format(TEXT("LOD {0}"), { LODIndex });
		PerLODCheckBoxes->AddSlot()
		.AutoWidth()
		.Padding(RightPadding)
		.VAlign(EVerticalAlignment::VAlign_Center)
		[
			SNew(SCheckBox)
			.IsChecked(this, &SAllowMorphTargetsPerLOD::IsAllowMorphTargetChecked, LODIndex)
			.OnCheckStateChanged(this, &SAllowMorphTargetsPerLOD::OnAllowMorphTargetChanged, LODIndex)
			[
				SNew(STextBlock)
				.Text(FText::FromString(LODHeader))
				.Font(FCoreStyle::GetDefaultFontStyle("Bold", 10))
			]
		];
	}	
}

ECheckBoxState SAllowMorphTargetsPerLOD::IsAllowMorphTargetChecked(const int32 LODIndex) const
{
	const ULODRecipe* LODRecipe = OwnerWidget.Pin()->GetLODRecipe();
	return LODRecipe->IsMorphTargetsAllowedInLOD(LODIndex) ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;
}

void SAllowMorphTargetsPerLOD::OnAllowMorphTargetChanged(ECheckBoxState NewCheckedState, int32 LODIndex)
{
	ULODRecipe* LODRecipe = OwnerWidget.Pin()->GetLODRecipe();
	if (NewCheckedState == ECheckBoxState::Checked)
		LODRecipe->AllowMorphTargetsInLOD(true, LODIndex);
	else
		LODRecipe->AllowMorphTargetsInLOD(false, LODIndex);
}

// Called when a property on the specified object is modified
void SAllowMorphTargetsPerLOD::OnPropertyChanged(UObject* ObjectBeingModified, FPropertyChangedEvent& PropertyChangedEvent)
{
	if (ULODRecipe* LODRecipe = Cast<ULODRecipe>(ObjectBeingModified))
	{
		const FName PropertyName(PropertyChangedEvent.Property->GetFName());
		if (PropertyName == GET_MEMBER_NAME_CHECKED(ULODRecipe, NumLODs))
		{
			RefreshPerLODCheckBoxes();
		}
	}
}
