// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.

#include "WidgetInteraction.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "IDisplayCluster.h"
#include "IDisplayClusterClusterManager.h"
#include "Engine.h"

#define LOCTEXT_NAMESPACE "FWidgetInteractionModule"

DEFINE_LOG_CATEGORY(WidgetIntLog);

void FWidgetInteractionModule::StartupModule()
{
  on_world_tick_start_delegate_.BindRaw(this, &FWidgetInteractionModule::OnWorldTickStart);
  FWorldDelegates::OnWorldTickStart.Add(on_world_tick_start_delegate_);
}

void FWidgetInteractionModule::ShutdownModule()
{
}


void FWidgetInteractionModule::OnWorldTickStart(ELevelTick level_tick, float val)
{
	//since OnWorldTickStart is called independent of the world/level we are in, 
	//we need to check whether the level changed and, if so, reattach the interaction component
	auto worlds = GEngine->GetWorldContexts();

	for (auto world_context : worlds) {

		auto world = world_context.World();

		if (last_world == world && widget_interaction_cmp_ != nullptr) {
			if (widget_interaction_cmp_->IsValidLowLevel() == true) {
				continue;
			}
			else {
				widget_interaction_cmp_ = nullptr;
			}
		}

		if (world == nullptr)
			continue;

		auto player_controller = world->GetFirstPlayerController();
		if (player_controller == nullptr)
			continue;

		auto vr_pawn = dynamic_cast<AVirtualRealityPawn*>(player_controller->AcknowledgedPawn);
		if (vr_pawn == nullptr)
			continue;

		CreateWidgetInteraction(vr_pawn->GetRightHandComponent(), vr_pawn);
		last_world = world;

		UE_LOG(WidgetIntLog, Verbose, TEXT("VRInteractionComponent attached to right hand"));
	}
}

UVRWidgetInteractionComponent* FWidgetInteractionModule::GetWidgetInteractionComponent() {
  return widget_interaction_cmp_;
}

void FWidgetInteractionModule::CreateWidgetInteraction(USceneComponent* parent, AVirtualRealityPawn* outer)
{
  widget_interaction_cmp_ = NewObject<UVRWidgetInteractionComponent>(outer, UVRWidgetInteractionComponent::StaticClass());
  widget_interaction_cmp_->Init(parent);
}

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FWidgetInteractionModule, WidgetInteraction)