// Project Sword & Gun Copyright © 2021 Kevin Poretti


#include "Controllers/SNGPlayerController.h"

void ASNGPlayerController::OnPossess(APawn* aPawn)
{
	Super::OnPossess(aPawn);
	
	if(Protagonist == nullptr)
	{
		Protagonist = Cast<ASNGProtagonist>(GetCharacter());
	}
	
	SetupInputs();
}

void ASNGPlayerController::OnUnPossess()
{
	Protagonist = nullptr;
}

void ASNGPlayerController::SetupInputs()
{
	check(Protagonist != nullptr);

	InputComponent->BindAxis("Turn", this, &ASNGPlayerController::AddYawInput);
	InputComponent->BindAxis("LookUp", this, &ASNGPlayerController::AddPitchInput);

	// have to figure out how to decouple these
	InputComponent->BindAxis("MoveForward", Protagonist, &ASNGProtagonist::MoveForward);
	InputComponent->BindAxis("MoveRight", Protagonist, &ASNGProtagonist::MoveRight);

	/*
	InputComponent->BindAction("Jump", IE_Pressed, Protagonist, &ASNGProtagonist::Jump);
	InputComponent->BindAction("Dash", IE_Pressed, Protagonist, &ASNGProtagonist::Dash);
	InputComponent->BindAction("MeleeAttack", IE_Pressed, Protagonist, &ASNGProtagonist::Attack);
	*/

	BindActionToCharacterCommand("Jump", "JUMP");
	BindActionToCharacterCommand("Dash", "DASH");
	BindActionToCharacterCommand("MeleeAttack", "ATTACK");
}

void ASNGPlayerController::BindActionToCharacterCommand(FName ActionName, FName CommandName)
{
	check(InputComponent != nullptr);
	
	FInputActionHandlerSignature ActionHandler;
	ActionHandler.BindUObject(this, &ASNGPlayerController::PushCharacterCommandToPawn, CommandName);
	
	FInputActionBinding ActionBinding(ActionName, IE_Pressed);
	ActionBinding.ActionDelegate = ActionHandler;
	InputComponent->AddActionBinding(ActionBinding);
}

void ASNGPlayerController::PushCharacterCommandToPawn(FName Command)
{
	FSNGEvent Event;
	Event.EventType = ESNGEventType::CHARACTER_COMMAND;
	Event.CommandData.CommandName = Command;

	// push event
	if(Protagonist->Implements<USNGEventProcessorInterface>())
	{
		ISNGEventProcessorInterface* EventProcessor = Cast<ISNGEventProcessorInterface>(Protagonist);
		EventProcessor->PushEvent(Event);
	}
}
