// Copyright Epic Games, Inc. All Rights Reserved.

#include "EndlessVendettaGameMode.h"
#include "EndlessVendettaCharacter.h"
#include "EVGameInstance.h"
#include "UObject/ConstructorHelpers.h"
#include "EndlessVendetta/AI/EnemyCharacter.h"
#include "EndlessVendetta/AI/AIControlHub.h"
#include "Kismet/GameplayStatics.h"
#include "Engine/DamageEvents.h"
#include "Misc/Guid.h"

AEndlessVendettaGameMode::AEndlessVendettaGameMode() : Super()
{
	// set default pawn class to our Blueprinted character
	static ConstructorHelpers::FClassFinder<APawn> PlayerPawnClassFinder(TEXT("/Game/FirstPerson/Blueprints/BP_FirstPersonCharacter"));
	DefaultPawnClass = PlayerPawnClassFinder.Class;

}

void AEndlessVendettaGameMode::KillAllEnemies()
{
	TArray<AActor*> EnemyCharacters;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), AEnemyCharacter::StaticClass(), EnemyCharacters);
	for (AActor* EnemyActor : EnemyCharacters)
	{
		AEnemyCharacter* EnemyCharacter = Cast<AEnemyCharacter>(EnemyActor);
		EnemyCharacter->TakeDamage(EnemyCharacter->MaxHealth, FDamageEvent(), GetWorld()->GetFirstPlayerController(), GetWorld()->GetFirstPlayerController()->GetOwner());
	}
}

void AEndlessVendettaGameMode::SetLocalAIAlertLevel(int NewAlertLevel)
{
	TArray<AActor*> AIControlHubActors;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), AAIControlHub::StaticClass(), AIControlHubActors);
	for (AActor* AIControlHubActor : AIControlHubActors)
	{
		AAIControlHub* AIControlHub = Cast<AAIControlHub>(AIControlHubActor);
		AIControlHub->SetPlayerLastKnownLocation();
		AIControlHub->SetAlertLevel(NewAlertLevel);
	}
}

void AEndlessVendettaGameMode::SendEvent(FString EventKey, FString EventData)
{
	const FString EventID = FGuid::NewGuid().ToString();
	const FString EventTime = FDateTime::Now().ToString();
	const auto Request = FHttpModule::Get().CreateRequest();
	Request->SetURL(TelemetryURLEvents);
	Request->SetVerb("POST");
	Request->SetHeader("Content-Type", "application/json");
	Request->SetHeader("Accept", "application/json");
	Request->SetContentAsString("{\"SessionID\":\"" + SessionID + "\",\"PlayerGUID\":\"" + PlayerGUID + "\",\"EventID\":\"" + EventID + "\",\"Timestamp\":\"" + EventTime + "\",\"EventKey\":\"" + EventKey + "\",\"EventData\":\"" + EventData + "\"}");
	Request->OnProcessRequestComplete().BindLambda([](FHttpRequestPtr request, FHttpResponsePtr response, bool success)
		{
			GLog->Log("Telemetry Event Response: " + response->GetContentAsString());
		});
	Request->ProcessRequest();
}

void AEndlessVendettaGameMode::BeginPlay()
{
	Super::BeginPlay();
	SessionID = Cast<UEVGameInstance>(GetGameInstance())->GlobalSessionID;
}
