using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace NodeCanvas.Tasks.Conditions {
	[Category("Reset")]
	public class CheckEnvironmentObserver : ConditionTask<PlayerEnvironmentManager>{

		public BBParameter<string> observerLabel;
		public BBParameter<RaycastHit> outputHitTo;

		protected override string info{
			get {
				return $"Check Environment Observer, [\"{observerLabel.value}\"]";
			}
		}
		
		//Use for initialization. This is called only once in the lifetime of the task.
		//Return null if init was successfull. Return an error string otherwise
		protected override string OnInit(){
			var observer = agent.FindObserverFromString(observerLabel.value);
			if (observer == null) {
				return $"An environment observer couldn't be found under the name {observerLabel.value}. Check your spelling and if it exists??";
			}

			return null;
		}

		//Called whenever the condition gets enabled.
		protected override void OnEnable() {
			agent.FindObserverFromString(observerLabel.value).active = true;
		}

		//Called whenever the condition gets disabled.
		protected override void OnDisable() {
			agent.FindObserverFromString(observerLabel.value).active = false;
		}

		//Called once per frame while the condition is active.
		//Return whether the condition is success or failure.
		protected override bool OnCheck(){
			if (agent.EvaluateFromString(observerLabel.value) == true) {
				if (outputHitTo.isDefined) {
					EnvironmentObserver hitObserver = agent.FindObserverFromString(observerLabel.value, agent.observers);
						
					if (hitObserver.hit.Equals(default(RaycastHit))) {
						Debug.LogError("You just tried to pull a RaycastHit for later use from an environment observer, but no RaycastHit is available. Don't forget that CastType.Box and CastType.Sphere CANNOT spit one out!");
					} else {
						outputHitTo.value = hitObserver.hit;
						return true;
					}
				}
				
				return true;
			}

			return false;
		}
	}
}