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


#include "EVGameInstance.h"

#include "Kismet/GameplayStatics.h"

void UEVGameInstance::CreateNewSaveGameInstance()
{
	if (UGameplayStatics::DoesSaveGameExist("MainSave", 0)) UGameplayStatics::DeleteGameInSlot("MainSave", 0);
	
	MainSaveGameInstanceRef = Cast<UMainSaveGameClass>(UGameplayStatics::CreateSaveGameObject(UMainSaveGameClass::StaticClass()));
	MainSaveGameInstanceRef->CurrentMainBountyIndexSave = 0;
	MainSaveGameInstanceRef->LastMainBountyIndexInOpenWorld = 0;
	MainSaveGameInstanceRef->MoneySave = 0;
	MainSaveGameInstanceRef->FavourSave = 0;
	UGameplayStatics::SaveGameToSlot(MainSaveGameInstanceRef, "MainSave", 0);
}

int UEVGameInstance::LoadSaveGameInstance()
{
	if (!UGameplayStatics::DoesSaveGameExist("MainSave", 0)) return 0;
	MainSaveGameInstanceRef = Cast<UMainSaveGameClass>(UGameplayStatics::LoadGameFromSlot("MainSave", 0));
	return MainSaveGameInstanceRef->CurrentMainBountyIndexSave;
}

void UEVGameInstance::DeleteSaveGameFiles()
{
	if (UGameplayStatics::DoesSaveGameExist("MainSave", 0)) UGameplayStatics::DeleteGameInSlot("MainSave", 0);
}

void UEVGameInstance::OnStart()
{
	Super::OnStart();
	GlobalSessionID = FGuid::NewGuid().ToString().Left(5).ToUpper();
	IsValidSessionID(GlobalSessionID);
}

void UEVGameInstance::IsValidSessionID(const FString& SessionID)
{
	const auto Request = FHttpModule::Get().CreateRequest();
	Request->SetURL("https://ev.api.philipwhite.dev/api/session/" + SessionID);
	Request->SetVerb("GET");
	Request->OnProcessRequestComplete().BindUObject(this, &UEVGameInstance::OnResponseReceived);
	Request->ProcessRequest();
}

void UEVGameInstance::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully)
{
	if (Response->GetResponseCode() == 200)
	{
		GLog->Log("Session ID Exists Regenerating");
		GlobalSessionID = FGuid::NewGuid().ToString().Left(5).ToUpper();
		IsValidSessionID(GlobalSessionID);
		return;
	}
	GLog->Log("Session ID is Valid");
}
