using UnityEngine;
using System.Collections;
using UnityEditor;

[AddComponentMenu("MGUB Event Editor/Trigger Event")]
public class Trigger : SceneEvent {
    public float radius = 10.0f;
    public Collider collider;

	// Update is called once per frame
	void Update () {
        if (lonelyRunning && scriptRunning != null && !running) {
            return;
        }
        if (!running && !completed) {
            bool interactable = true;
            for (int i = 0; i < conditions.Count; i++) {    // This check is already done inside "Run" function, but this way we can prevent calling "IsInside" for every trigger
                if (!conditions[i].Test()) {
                    interactable = false;
                    break;
                }
            }
            if (!collider.enabled) {
                collider.enabled = interactable;
            }
            Vector3 interactorPosition;
            if (ThirdPersonController.main != null) {
                interactorPosition = ThirdPersonController.main.transform.position;
            }
            else {
                interactorPosition = Camera.main.transform.position;
            }
            if (interactable && IsInside(collider, interactorPosition)) {
                Run();
            }
        }
        else {
            if (collider.enabled) {
                collider.enabled = false;
            }
            Run();
        }
	}

    public static bool IsInside(Collider c, Vector3 point) {
        Vector3 closest = c.ClosestPoint(point);
        return Vector3.Distance(closest, point) < 0.01f;
    }

    public void Reset() {
        BoxCollider boxCollider = this.gameObject.AddComponent<BoxCollider>();
        boxCollider.isTrigger = true;
        this.collider = boxCollider;
        this.gameObject.layer = 18;
    }

    /*
    #if UNITY_EDITOR
        [MenuItem("GameObject/MGUB Event System/Trigger", false, 10)]
        static void CreateTrigger(MenuCommand menuCommand) {
            GameObject parent = menuCommand.context as GameObject;
            if (parent != null) {
                GameObject go = new GameObject(parent.name.Replace(" ", "") + "Trigger");
                go.AddComponent<Trigger>();
                GameObjectUtility.SetParentAndAlign(go, parent);
                Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
                Selection.activeObject = go;
            }
        }
    #endif
    */
}
