using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace Leap.Unity
{
	public class DetectorLogicGate : Detector
	{
		public void AddDetector(Detector detector)
		{
			if (!this.Detectors.Contains(detector))
			{
				this.Detectors.Add(detector);
				this.activateDetector(detector);
			}
		}

		public void RemoveDetector(Detector detector)
		{
			detector.OnActivate.RemoveListener(new UnityAction(this.CheckDetectors));
			detector.OnDeactivate.RemoveListener(new UnityAction(this.CheckDetectors));
			this.Detectors.Remove(detector);
		}

		public void AddAllSiblingDetectors()
		{
			Detector[] components = base.GetComponents<Detector>();
			for (int i = 0; i < components.Length; i++)
			{
				if (components[i] != this && components[i].enabled)
				{
					this.AddDetector(components[i]);
				}
			}
		}

		private void Awake()
		{
			for (int i = 0; i < this.Detectors.Count; i++)
			{
				this.activateDetector(this.Detectors[i]);
			}
			if (this.AddAllSiblingDetectorsOnAwake)
			{
				this.AddAllSiblingDetectors();
			}
		}

		private void activateDetector(Detector detector)
		{
			detector.OnActivate.RemoveListener(new UnityAction(this.CheckDetectors));
			detector.OnDeactivate.RemoveListener(new UnityAction(this.CheckDetectors));
			detector.OnActivate.AddListener(new UnityAction(this.CheckDetectors));
			detector.OnDeactivate.AddListener(new UnityAction(this.CheckDetectors));
		}

		private void OnEnable()
		{
			this.CheckDetectors();
		}

		private void OnDisable()
		{
			this.Deactivate();
		}

		protected void CheckDetectors()
		{
			if (this.Detectors.Count < 1)
			{
				return;
			}
			bool flag = this.Detectors[0].IsActive;
			for (int i = 1; i < this.Detectors.Count; i++)
			{
				if (this.GateType == LogicType.AndGate)
				{
					flag = (flag && this.Detectors[i].IsActive);
				}
				else
				{
					flag = (flag || this.Detectors[i].IsActive);
				}
			}
			if (this.Negate)
			{
				flag = !flag;
			}
			if (flag)
			{
				this.Activate();
			}
			else
			{
				this.Deactivate();
			}
		}

		[SerializeField]
		[Tooltip("The list of observed detectors.")]
		private List<Detector> Detectors;

		[Tooltip("Add all detectors on this object automatically.")]
		public bool AddAllSiblingDetectorsOnAwake = true;

		[Tooltip("The type of logic used to combine detector state.")]
		public LogicType GateType;

		[Tooltip("Whether to negate the gate output.")]
		public bool Negate;
	}
}
