// Oleg Petruny proprietary.

#include "DialogueRowWidgetManager.h"

#include "Blueprint/WidgetTree.h"
#include "Components/TextBlock.h"
#include "Components/VerticalBox.h"

#include "CommonFunctions.h"
#include "DialogueManager.h"
#include "Widgets/DialogueRowWidget.h"
#include "Widgets/DialogueSkipWidget.h"

void UDialogueRowWidgetManager::SetInput(const FKey key, const FText desc, FDialogueSkipDelegate& delegate)
{
    dialogueSkipWidget->keyText->SetText(UCommonFunctions::GetKeyDisplayName(key));
    dialogueSkipWidget->descriptionText->SetText(desc);
    dialogueSkipWidget->skipDialogueDelegate = delegate;
}

void UDialogueRowWidgetManager::Append(const FDialogueRow& dialogue)
{
    FScopeLock Lock(&rowsLock);

    for(int32 i = rows->GetChildrenCount() - rowsIds.Num(); i < 1; ++i)
    {
        auto row = WidgetTree->ConstructWidget<UDialogueRowWidget>(rowWidgetClass);
        row->SetVisibility(ESlateVisibility::Hidden);
        rows->AddChild(row);
    }

    auto row = Cast<UDialogueRowWidget>(rows->GetChildAt(rowsIds.Num()));
    row->text->SetText(dialogue.text);
    row->SetStyle(dialogue.type);
    row->SetVisibility(ESlateVisibility::Visible);

    rowsIds.Add(dialogue.id);

    if(dialogue.type == EDialogueWaveType::Main)
    {
        if(count == 0)
            dialogueSkipWidget->SetVisibility(ESlateVisibility::Visible);
        ++count;
    }
}

void UDialogueRowWidgetManager::Remove(const struct FDialogueRow& dialogue)
{
    FScopeLock Lock(&rowsLock);

    if(dialogue.id == "")
    {
        for(int32 i = 0; i < rowsIds.Num(); ++i)
            rows->GetChildAt(i)->SetVisibility(ESlateVisibility::Hidden);
        rowsIds.Empty();

        return;
    }

    if(!rowsIds.Contains(dialogue.id))
        return;

    int32 index = rowsIds.Find(dialogue.id);
    auto row = rows->GetChildAt(index);
    row->SetVisibility(ESlateVisibility::Hidden);
    rows->RemoveChildAt(index);
    rows->AddChild(row);

    rowsIds.Remove(dialogue.id);

    if(dialogue.type == EDialogueWaveType::Main)
    {
        if(count == 1)
            dialogueSkipWidget->SetVisibility(ESlateVisibility::Hidden);
        --count;
    }
}

void UDialogueRowWidgetManager::AnimateSkipWidget(const EInputAnimatedWidgetAnimation animation)
{
    dialogueSkipWidget->RunAnimation(animation);
}
