// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "SkillBrowserSubMenu.h"
#include "MenuController.h"
#include "SkillTreeWidget.h"
#include "SkillTreeObject.h"
#include "BaseSkillObject.h"
#include "SkillWidget.h"

void USkillBrowserItem::NativeConstruct()
{
	Super::NativeConstruct();
}

void USkillBrowserItem::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
	Super::NativeTick(MyGeometry, InDeltaTime);

	if(skillTree->IsUsingSkill(skillObject))
	{
		this->SetIsEnabled(false);
	}
	else
	{
		this->SetIsEnabled(true);
	}
}
void USkillBrowserItem::Init(UAbilityInfo* info)
{
	ability = info;
	OnInit();
}

void USkillBrowserItem::NativeOnSelectionChanged(bool selected, bool controller)
{
	Super::NativeOnSelectionChanged(selected, controller);
	if(selected && category && controller)
	{
		UScrollBox* sb = Cast<UScrollBox>(category->Slot->Parent);
		if(sb)
		{
			sb->ScrollWidgetIntoView(category);
		}
	}
}

void USkillBrowserItem::NativeOnPressed(bool controllerInput)
{
	Super::NativeOnPressed(controllerInput);

	if(!GetIsEnabled())
		return;

	USkillWidget* wdg = skillTree->NewSkillFromAsset(skillObject, controllerInput);
	wdg->SetSelectedEffect(skillObject->abilityEffects.IndexOfByKey(ability));
	if(controllerInput)
		GetSubMenu()->GetScreen()->OpenSubMenu(wdg);
}

void USkillBrowserSubMenu::NativeConstruct()
{
	m_skillItemContainer = Cast<UPanelWidget>(WidgetTree->FindWidget("ItemContainer"));
	AMenuController* menuController = Cast<AMenuController>(GetOwningPlayer());
	USkillTreeWidget* skillTree = menuController->skillTree;
	USkillTreeObject* skObject = skillTree->skillTreeAsset;

	for(int32 i = 0; i < skObject->skills.Num(); i++)
	{
		UBaseSkillObject* skill = skObject->skills[i]->GetDefaultObject<UBaseSkillObject>();

		// Create a category item
		USkillBrowserItemCategory* categoryItem = CreateWidget<USkillBrowserItemCategory>(GetWorld(), itemCategoryClass);
		if(!categoryItem)
		{
			GERROR("Failed to create skill browser item category");
			continue;
		}

		m_skillItemContainer->AddChild(categoryItem);
		categoryItem->skillObject = skill;

		// Add all the abilities to this category
		for(int32 j = 0; j < skill->abilityEffects.Num(); j++)
		{
			UAbilityInfo* effect = skill->abilityEffects[j];
			if(!effect)
				continue;
			USkillBrowserItem* item = CreateWidget<USkillBrowserItem>(GetWorld(), itemClass);
			if(!item)
			{
				GERROR("Failed to create skill browser item");
				continue;
			}
			item->skillObject = skill;
			item->skillTree = skillTree;
			item->category = categoryItem;
			categoryItem->itemContainer->AddChild(item);

			// Call init on ability item
			item->Init(effect);
		}

		// Call init on category
		categoryItem->OnInit();
	}

	Super::NativeConstruct();
}

void USkillBrowserItemCategory::NativeConstruct()
{
	itemContainer = Cast<UPanelWidget>(WidgetTree->FindWidget("ItemContainer"));
}
