// Oleg Petruny proprietary.


#include "MainGameModeBase.h"

#include "Engine/World.h"
#include "GameFramework/SpectatorPawn.h"
#include "Kismet/GameplayStatics.h"
#include "UObject/ScriptInterface.h"

#include "CustomGameInstanceBase.h"
#include "Widgets/WidgetsManager.h"

UWidgetsManager* AMainGameModeBase::_widgetsManager = nullptr;

void AMainGameModeBase::StartPlay()
{
    AGameModeBase::StartPlay();

    _widgetsManager = NewObject<UWidgetsManager>(this, widgetManagerClass);
    _widgetsManager->Init();
}

bool AMainGameModeBase::SetPause(APlayerController* PC, FCanUnpause CanUnpauseDelegate)
{
    if(_widgetsManager)
    {
        if(IsPaused())
        {
            _widgetsManager->HideOverlayWidgets();
        }
        else
        {
            _widgetsManager->ShowOverlayWidgets();
        }
    }

    return AGameModeBase::SetPause(PC, CanUnpauseDelegate);
}

UWidgetsManager* AMainGameModeBase::GetWidgetManager()
{
    return _widgetsManager;
}

void AMainGameModeBase::SwitchCameraMode()
{
    static TWeakObjectPtr<APawn> _playerPawn = nullptr;

    if(auto PC = UGameplayStatics::GetPlayerController(GetWorld(), 0))
    {
        if(auto pawn = PC->GetPawn())
        {
            if(!_playerPawn.IsValid())
            {
                auto spawnLoc = pawn->GetActorLocation();
                auto spawnRot = pawn->GetActorRotation();
                if(auto cameraPawn = GetWorld()->SpawnActor<APawn>(SpectatorClass, spawnLoc, spawnRot))
                {
                    _playerPawn = pawn;
                    PC->Possess(cameraPawn);
                }
            }
            else
            {
                PC->Possess(_playerPawn.Get());
                pawn->Destroy();
                _playerPawn = nullptr;
            }
        }
    }

    if(_widgetsManager)
    {
        _widgetsManager->UpdateOverlayWidgetsOwner();
    }
}
