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


#include "DDIPlayerController.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "GameFramework/Character.h"

ADDIPlayerController::ADDIPlayerController()
{
	
}


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

	if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(GetLocalPlayer()))
	{
		for (UInputMappingContext* CurrentContext : MappingContexts)
		{
			Subsystem->AddMappingContext(CurrentContext, 0);
		}
	}
	
}

void ADDIPlayerController::SetupInputComponent()
{
	Super::SetupInputComponent();
	
	if (UEnhancedInputComponent* Subsystem = Cast<UEnhancedInputComponent>(InputComponent))
	{
		if (MoveAction)	Subsystem->BindAction(MoveAction, ETriggerEvent::Triggered, this, &ADDIPlayerController::Move);
		if (LookAction) Subsystem->BindAction(LookAction, ETriggerEvent::Triggered, this, &ADDIPlayerController::Look);
		if (JumpAction)
		{
			Subsystem->BindAction(JumpAction, ETriggerEvent::Started, this, &ADDIPlayerController::Jump);
			Subsystem->BindAction(JumpAction, ETriggerEvent::Completed, this, &ADDIPlayerController::JumpEnd);
		}
	}
}

void ADDIPlayerController::OnPossess(APawn* InPawn)
{
	Super::OnPossess(InPawn);

	// is this a shooter character?
	// if (ADDICharacter* DDICharacter = Cast<ADDICharacter>(InPawn))
	// {
	// 	// add the player tag
	// 	DDICharacter->Tags.Add(PlayerPawnTag);
	// }
}

void ADDIPlayerController::Move(const FInputActionValue& Value)
{
	const FVector2D MovementVector = Value.Get<FVector2D>();

	if (APawn* ControlledPawn = GetPawn())
	{
		FRotator CameraRotation = GetControlRotation();
		FRotator YawRotation(0.f, CameraRotation.Yaw, 0.f);

		FVector ForwardDiection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);

		ControlledPawn->AddMovementInput(ForwardDiection, MovementVector.Y);
		ControlledPawn->AddMovementInput(RightDirection,MovementVector.X);
		
	}
}

void ADDIPlayerController::Look(const FInputActionValue& Value)
{
	const FVector2D LookAxisVector = Value.Get<FVector2D>()*mouseSensitivity; //Added mouseSensitivity

	if (APawn* ControlledPawn = GetPawn())
	{
		AddYawInput(LookAxisVector.X);
		AddPitchInput(LookAxisVector.Y);
	}
}

void ADDIPlayerController::Jump(const FInputActionValue& Value)
{
	if (ACharacter* character = GetCharacter())
	{
		character->Jump();
	}
}

void ADDIPlayerController::JumpEnd(const FInputActionValue& Value)
{
	if (ACharacter* character = GetCharacter())
	{
		character->StopJumping();
	}
}