// Copyright (c) 2019-2022 Drowning Dragons Limited. All Rights Reserved.

#include "EndlessVendetta/MyVICharacterBase.h"
#include "Pawn/VICharacterBase.h"
#include "Net/UnrealNetwork.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Pawn/VIPawnVaultComponent.h"
#include "MotionWarpingComponent.h"
#include "VIBlueprintFunctionLibrary.h"

void AMyVICharacterBase::BeginPlay()
{
	Super::BeginPlay();

	VaultComponent = IVIPawnInterface::Execute_GetPawnVaultComponent(this);
	MotionWarpingComponent = IVIPawnInterface::Execute_GetMotionWarpingComponent(this);
}

void AMyVICharacterBase::CheckJumpInput(float DeltaTime)
{
	const bool bIsVaulting = IsVaulting();

	// Server update simulated proxies with correct vaulting state
	if (GetLocalRole() == ROLE_Authority && GetNetMode() != NM_Standalone)
	{
		bRepIsVaulting = bIsVaulting;
	}

	// Try to vault from local input
	if (IsLocallyControlled() && VaultComponent)
	{
		// Disable jump if vaulting
		if (VaultComponent->bPressedVault)
		{
			bPressedJump = false;
		}

		// Possibly execute vault
		if (GetCharacterMovement())
		{
			VaultComponent->CheckVaultInput(DeltaTime, GetCharacterMovement()->MovementMode);
		}
		else
		{
			VaultComponent->CheckVaultInput(DeltaTime);
		}
	}

	// Pick up changes in vaulting state to change movement mode
	// to something other than flying (required for root motion on Z)
	if (bWasVaulting && !bIsVaulting)
	{
		StopVaultAbility();
	}

	// Call super so we actually jump if we're meant to
	Super::CheckJumpInput(DeltaTime);

	// Cache end of frame
	bWasVaulting = bIsVaulting;
}

void AMyVICharacterBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME_CONDITION(AMyVICharacterBase, bRepIsVaulting, COND_SimulatedOnly);
	DOREPLIFETIME_CONDITION(AMyVICharacterBase, RepMotionMatch, COND_SimulatedOnly);
}

void AMyVICharacterBase::Jump()
{
	// If missing critical components then jump and exit
	if (!VaultComponent || !GetCharacterMovement())
	{
		UE_LOG(LogTemp, Warning, TEXT("no vault comp or character movement"));
		Super::Jump();
		return;
	}

	// Either jump or vault, determined by VaultComponent::EVIJumpKeyPriority
	if (VaultComponent->Jump(GetCharacterMovement()->GetGravityZ(), CanJump(), GetCharacterMovement()->IsFalling()))
	{
		UE_LOG(LogTemp, Warning, TEXT("gravity Z: %f"), GetCharacterMovement()->GetGravityZ());
		// Jump normally
		Super::Jump();
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("try to vault"));
		// Jump key essentially presses the vault input
		VaultComponent->Vault();
	}
}

void AMyVICharacterBase::StopJumping()
{
	Super::StopJumping();

	// Release vault input if the jump key pressed vault instead
	if (VaultComponent)
	{
		VaultComponent->StopJumping();
	}
}

void AMyVICharacterBase::StartVaultAbility_Implementation()
{
	// Called by GA_Vault
	// Need to be in flying mode to have root motion on Z axis
	if (GetCharacterMovement() && GetLocalRole() > ROLE_SimulatedProxy)
	{
		GetCharacterMovement()->SetMovementMode(MOVE_Flying);
	}
}

void AMyVICharacterBase::StopVaultAbility()
{
	// Called by CheckJumpInput()
	// Exiting flying mode
	// This may put is straight into falling if we aren't properly grounded, which is fine
	if (GetCharacterMovement() && GetLocalRole() > ROLE_SimulatedProxy)
	{
		GetCharacterMovement()->SetMovementMode(GetCharacterMovement()->GetGroundMovementMode());
	}

	OnStopVaultAbility();
}

void AMyVICharacterBase::OnRep_MotionMatch()
{
	// Simulated proxies update their sync points here, sent from the server during GA_Vault
	MotionWarpingComponent->AddOrUpdateWarpTargetFromLocationAndRotation(TEXT("VaultSyncPoint"), RepMotionMatch.Location, RepMotionMatch.Direction.Rotation());
}

bool AMyVICharacterBase::IsVaulting() const
{
	// Simulated proxies use the value provided by server
	if (GetLocalRole() == ROLE_SimulatedProxy)
	{
		return bRepIsVaulting;
	}

	// Local and authority uses gameplay tags for a predicted result
	if (VaultComponent)
	{
		return VaultComponent->IsVaulting();
	}

	return false;
}

// *********************************************** //
// ******** Begin Pawn Vaulting Interface ******** //
// *********************************************** //

UVIPawnVaultComponent* AMyVICharacterBase::GetPawnVaultComponent_Implementation() const
{
	// You need to override this
	UVIBlueprintFunctionLibrary::MessageLogError(FString::Printf(TEXT("AVICharacterBase::GetPawnVaultComponent not implemented for { %s }. Cannot Vault."), *GetName()));
	return nullptr;
}

UMotionWarpingComponent* AMyVICharacterBase::GetMotionWarpingComponent_Implementation() const
{
	// You need to override this
	UVIBlueprintFunctionLibrary::MessageLogError(FString::Printf(TEXT("AVICharacterBase::GetMotionWarpingComponent not implemented for { %s }. Cannot Vault."), *GetName()));
	return nullptr;
}

FVIAnimSet AMyVICharacterBase::GetVaultAnimSet_Implementation() const
{
	// You need to override this
	UVIBlueprintFunctionLibrary::MessageLogError(FString::Printf(TEXT("AVICharacterBase::GetVaultAnimSet not implemented for { %s }. Cannot Vault."), *GetName()));
	return FVIAnimSet();
}

FVITraceSettings AMyVICharacterBase::GetVaultTraceSettings_Implementation() const
{
	// You need to override this
	UVIBlueprintFunctionLibrary::MessageLogError(FString::Printf(TEXT("AVICharacterBase::GetVaultTraceSettings not implemented for { %s }. Using default trace settings."), *GetName()), false);
	return FVITraceSettings();
}

FVector AMyVICharacterBase::GetVaultDirection_Implementation() const
{
	// Use input vector if available
	if (GetCharacterMovement() && !GetCharacterMovement()->GetCurrentAcceleration().IsNearlyZero())
	{
		return GetCharacterMovement()->GetCurrentAcceleration();
	}

	// Use character facing direction if not providing input
	return GetActorForwardVector();
}

bool AMyVICharacterBase::CanVault_Implementation() const
{
	// Vaulting must finish before starting another vault attempt
	if (IsVaulting())
	{
		UE_LOG(LogTemp, Warning, TEXT("is already vaulting"));
		return false;
	}

	// Invalid components
	if (!VaultComponent || !GetCharacterMovement())
	{
		UE_LOG(LogTemp, Warning, TEXT("invalid componets for vaulting"));
		return false;
	}

	// Animation instance is required to play vault montage
	if (!IsValid(FP_SkeletalMesh) || !IsValid(FP_SkeletalMesh->GetAnimInstance()))
	{
		UE_LOG(LogTemp, Warning, TEXT("Animation instance is required to play vault montage"));
		return false;
	}

	// Authority not initialized (this isn't set on clients)
	if (HasAuthority() && !VaultComponent->bVaultAbilityInitialized)
	{
		UE_LOG(LogTemp, Warning, TEXT("Authority not initialized (this isn't set on clients), hence cant vault"));
		return false;
	}

	// Exit if character is in a state they cannot vault from
	if (GetCharacterMovement()->IsMovingOnGround() || GetCharacterMovement()->IsFalling() || GetCharacterMovement()->IsSwimming())
	{
		if (GetCharacterMovement()->IsMovingOnGround() && !VaultComponent->bCanVaultFromGround)
		{
			UE_LOG(LogTemp, Warning, TEXT("cant vault cuz on the ground and cant vault from ground"));
			return false;
		}

		if (GetCharacterMovement()->IsFalling() && !VaultComponent->bCanVaultFromFalling)
		{
			UE_LOG(LogTemp, Warning, TEXT("cant vault cuz is falling and cant vault from falling"));
			return false;
		}

		if (GetCharacterMovement()->IsSwimming() && !VaultComponent->bCanVaultFromSwimming)
		{
			UE_LOG(LogTemp, Warning, TEXT("cant vault from swimming"));
			return false;
		}
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("cant vault  cuz isnt either swimming, walking on the ground or falling"));
		return false;
	}

	// Can't vault while crouching
	if (!VaultComponent->bCanVaultFromCrouching && GetCharacterMovement()->IsCrouching())
	{
		UE_LOG(LogTemp, Warning, TEXT("cant vault  cuz is crouching"));
		return false;
	}

	UE_LOG(LogTemp, Warning, TEXT("actually can vault"));
	// Passed all conditions
	return true;
}

void AMyVICharacterBase::OnLocalPlayerVault_Implementation(const FVector& Location, const FVector& Direction)
{
	// LocalPlayer just stores the data in the same place for convenience, ease of use, memory reduction, etc
	RepMotionMatch = FVIRepMotionMatch(Location, Direction);
}

void AMyVICharacterBase::GetVaultLocationAndDirection_Implementation(FVector& OutLocation, FVector& OutDirection) const
{
	// Because LocalPlayer stores in the same place, no need for any testing as they all use RepMotionMatch to store this

	// This is only currently used for FBIK tracing
	OutLocation = RepMotionMatch.Location;
	OutDirection = RepMotionMatch.Direction;
}

void AMyVICharacterBase::ReplicateMotionMatch_Implementation(const FVIRepMotionMatch& MotionMatch)
{
	// GA_Vault has directed server to update it's RepMotionMatch property so that it will
	// be replicated to simulated proxies with 1 decimal point of precision (net quantization)
	RepMotionMatch = MotionMatch;
}

bool AMyVICharacterBase::IsWalkable_Implementation(const FHitResult& HitResult) const
{
	// Surface we hit can be walked on or not
	return GetCharacterMovement() && GetCharacterMovement()->IsWalkable(HitResult);
}

bool AMyVICharacterBase::CanAutoVaultInCustomMovementMode_Implementation() const
{
	return true;

	// Example usage commented out

	/*
	
	if (GetCharacterMovement())
	{
		switch (GetCharacterMovement()->CustomMovementMode)
		{
		case 0:
			return false;
		case 1:  // Some example custom mode where auto vault can work
			return true;
		case 2:
			return false;
		default:
			return true;
		}
	}

	*/
}

// *********************************************** //
// ********* End Pawn Vaulting Interface ********* //
// *********************************************** //