﻿using UnityEngine;
using RootMotion.FinalIK;

namespace HutongGames.PlayMaker.Actions
{
	[ActionCategory("Final IK")]
	[Tooltip("Triggers an interaction with the InteractionSystem when character is in range of an InteractionTrigger.")]
	public class TriggerInteraction : InteractionAction
	{

		[Tooltip("Can this InteractionSystem be triggered?")]
		public FsmBool canTrigger;

		private GameObject intGO;
		private InteractionSystem intSys;

		public override void Reset()
		{
			base.Reset();

			intGO = null;
			intSys = null;
			canTrigger = new FsmBool() { UseVariable = true };
		}

		public override void OnUpdate()
		{
			if (!canTrigger.Value) return;

			if (intGO == null) intGO = Fsm.GetOwnerDefaultTarget(interactionSystem);
			if (intGO == null) return;

			if (intSys == null) intSys = intGO.GetComponent<InteractionSystem>();
			if (intSys == null)
			{
				Debug.LogWarning("No InteractionSystem component found on " + intGO.name);
				return;
			}

			Action(intSys);
		}

		protected override void Action(InteractionSystem sys)
		{
			if (!canTrigger.Value) return;

			// If not paused, find the closest InteractionTrigger that the character is in contact with
			int closestTriggerIndex = sys.GetClosestTriggerIndex();

			// ...if none found, do nothing
			if (closestTriggerIndex == -1) return;

			// ...if the effectors associated with the trigger are in interaction, do nothing
			if (!sys.TriggerEffectorsReady(closestTriggerIndex)) return;

			sys.TriggerInteraction(closestTriggerIndex, false);
		}
	}
}
