// Oleg Petruny proprietary.

#include "CustomGameInstance.h"

#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetSystemLibrary.h"

#include "ContentLoader.h"
#include "Levels/LevelBase.h"
#include "PlayerBase.h"
#include "SaveData.h"

UCustomGameInstance* UCustomGameInstance::instance = nullptr;

void UCustomGameInstance::Init()
{
    UGameInstance::Init();

    instance = this;
    contentLoader = NewObject<UContentLoader>(this);
    saveData = Cast<USaveData>(UGameplayStatics::CreateSaveGameObject(USaveData::StaticClass()));
}

UCustomGameInstance* UCustomGameInstance::Get()
{
    return instance;
}

UContentLoader* UCustomGameInstance::GetContentLoader()
{
    if(auto GI = Get())
        return GI->contentLoader;

    return nullptr;
}

void UCustomGameInstance::SaveGame(FName checkpointName)
{
    auto levelScript = ALevelBase::Get();
    if(!levelScript)
        return;

    auto player = APlayerBase::Get();
    if(!player)
        return;

    saveData->level = GetWorld()->GetFName();
    saveData->state = levelScript->GetState();
    saveData->checkpoint = checkpointName;
    if(player->leftPocketItem)
        saveData->playerLeftPocketItem = player->leftPocketItem->GetFName();
    else
        saveData->playerLeftPocketItem = FName(TEXT(""));
    if(player->rightPocketItem)
        saveData->playerRightPocketItem = player->rightPocketItem->GetFName();
    else
        saveData->playerRightPocketItem = FName(TEXT(""));

    UGameplayStatics::SaveGameToSlot(saveData, TEXT("Save"), 0);
}

void UCustomGameInstance::LoadGame()
{
    saveData = Cast<USaveData>(UGameplayStatics::LoadGameFromSlot(TEXT("Save"), 0));
    if(!saveData)
        return;

    UGameplayStatics::OpenLevel(this, saveData->level);
}

void UCustomGameInstance::ExitGame()
{
    UKismetSystemLibrary::QuitGame(GetWorld(), nullptr, EQuitPreference::Quit, true);
}
