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


#include "Widget/CommonBtn/CsdkCommonBtns.h"

#include "Blueprint/UserWidget.h"


void UCsdkCommonBtns::SynchronizeProperties()
{
	Super::SynchronizeProperties();

	if(bCanMutex)
	{
		DefaultIndex = FMath::Clamp(DefaultIndex,-1,BtnParams.Num() - 1);
	}
	else
	{
		bCanSelfMutex = false;
		DefaultIndex = -1;
	}

	if(MyCsdkCommonBtns.IsValid())
	{
		MyCsdkCommonBtns->SetOrientation(Orientation);
		MyCsdkCommonBtns->SetPadding(Padding);
	}
}

void UCsdkCommonBtns::ReleaseSlateResources(bool bReleaseChildren)
{
	Super::ReleaseSlateResources(bReleaseChildren);
	MyCsdkCommonBtns.Reset();
	BtnSlotSlate.Empty();
	BtnSlotWidgets.Empty();
}



TSharedRef<SWidget> UCsdkCommonBtns::RebuildWidget()
{
	Reset();

	MyCsdkCommonBtns = SNew(SCsdkCommonBtns)
	.Orientation(Orientation)
	.BtnNum(BtnParams.Num())
	.SlotWidgets(BtnSlotSlate)
	.Padding(Padding)
	.OnClicked(BIND_UOBJECT_DELEGATE(FCsdkSCommonBtnClicked, SlateHandleClicked));
            

	return MyCsdkCommonBtns.ToSharedRef();
}

void UCsdkCommonBtns::SwitchToIndex(const int32 Index)
{
	SlateHandleClicked(Index);
}

void UCsdkCommonBtns::Reset()
{
	DefaultIndex = FMath::Clamp(DefaultIndex,-1,BtnParams.Num() - 1);
	CurrentIndex = DefaultIndex;
	BtnSlotWidgets.Empty();
	BtnSlotSlate.Empty();

	if(BtnSlotClass->IsValidLowLevel())
	{
		for (int32 i = 0; i <BtnParams.Num(); ++i)
		{
			auto BtnSlotWidget = CreateWidget<UCsdkBaseBtnSlotWidget>(this, BtnSlotClass);
			check(BtnSlotWidget->IsValidLowLevel());
		
			BtnSlotWidget->BtnParam = BtnParams[i];
			BtnSlotWidgets.Add(BtnSlotWidget);
			BtnSlotSlate.Add(BtnSlotWidget->TakeWidget());

			if(i == CurrentIndex)
			{
				BtnSlotWidget->OnSlotWidgetPressed();
			}
		}
	}

}

FReply UCsdkCommonBtns::SlateHandleClicked(const int32 Index)
{
	if(bCanMutex)
	{
		if(CurrentIndex == Index)
		{
			if(bCanSelfMutex)
			{
				BtnSlotWidgets[Index]->OnSlotWidgetReleased();
				CurrentIndex = -1;
				OnClicked.Broadcast(CurrentIndex, FCsdkBtnParam{});
				return FReply::Handled();
			
			}
			else
			{
				return  FReply::Handled();
			}
		}
		else
		{
			BtnSlotWidgets[Index]->OnSlotWidgetPressed();
			if(CurrentIndex >= 0)
			{
				BtnSlotWidgets[CurrentIndex]->OnSlotWidgetReleased();
			}
			CurrentIndex = Index;
			OnClicked.Broadcast(CurrentIndex, BtnParams[CurrentIndex]);
		}
	}
	else //非互斥模式
	{
		CurrentIndex = Index;
		OnClicked.Broadcast(CurrentIndex, BtnParams[CurrentIndex]);
	}
	return FReply::Handled();
}
