using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;

[AddComponentMenu("MGUB Event Editor/Interactive Event")]
public class InteractiveTrigger : SceneEvent {
    public string interactionName = "Use";
    public bool automaticMovementDeactivation = true;
    public float activationDistance = 1.0f;
    public Vector3 activationOffset = Vector3.zero;
    public float angularView = 180.0f;
    public bool interactable = true;
    public float directionFactor = 0.0f;
    private static List<InteractiveTrigger> interactors = new List<InteractiveTrigger>();
    public static InteractiveTrigger lastFacingInteractor;

    private void Start() {
        CheckIfPresent();
    }

    private void CheckIfPresent() {
        if (!interactors.Contains(this)) {
            interactors.Add(this);
        }
    }

    // Update is called once per frame
    void Update () {
        CheckIfPresent();
        interactable = false;
        directionFactor = 999.0f;
        if (lonelyRunning && scriptRunning != null && !running) {
            return;
        }

        // If the event has not been executed already...

        if (!running && !completed) {
            Transform interactor;
            bool firstPerson = false;
            if (ThirdPersonController.main != null) {
                interactor = ThirdPersonController.main.transform;
                firstPerson = ThirdPersonController.main.firstPerson;
            }
            else {
                interactor = Camera.main.transform;
            }
            if (GameInputManager.main.isControllable && Vector3.Distance(transform.position + activationOffset, interactor.position + new Vector3(0.0f, 0.5f, 0.0f)) <= activationDistance) {
                Vector3 targetDir = interactor.position - transform.position;
                float angle = Vector3.Angle(targetDir, transform.forward);
                if (angle <= angularView) {
                    Vector3 charDir = transform.position - interactor.position + activationOffset;
                    float angleB;
                    if (!firstPerson) {
                        angleB = Vector3.Angle(charDir, interactor.forward);
                    }
                    else {
                        angleB = Vector3.Angle(charDir, Camera.main.transform.forward);
                    }
                    directionFactor = angleB;
                    if (angleB < 70) {
                        interactable = true;
                        for (int i = 0; i < conditions.Count; i++) {
                            if (!conditions[i].Test()) {
                                interactable = false;
                                break;
                            }
                        }
                    }
                }
            }
            if (interactable && !PauseMenu.paused) {
                if (!IsFacingSomeoneElse()) {
                    lastFacingInteractor = this;
                    if (/*Input.GetButtonDown("Action")*/ GameInputManager.actionButtonDown) {
                        Run();
                    }
                }
            }
            else {
                interactable = false;
            }
        }
        else {
            Run();
        }
	}

    private void OnDestroy() {
        if (interactors.Contains(this)) {
            interactors.Remove(this);
        }
        if (lastFacingInteractor == this) {
            lastFacingInteractor = null;
        }
    }

    void OnDrawGizmosSelected() {
        Color oldGizmoColor = Gizmos.color;
        DrawDefaultGizmoz();
        Gizmos.color = new Color(0.0f, 0.25f, 1.0f);
        Gizmos.DrawWireSphere(transform.position + activationOffset, activationDistance);
        Gizmos.color = oldGizmoColor;
    }

    public override void OnEventStart() {
        base.OnEventStart();
        if (automaticMovementDeactivation && ThirdPersonController.main != null) {
            Action a1 = new Action(this);
            a1.type = Action.types.enable_movement;
            a1.boolValue1 = false;
            a1.Execute();
        }
    }

    public override void OnEventEnd() {
        base.OnEventEnd();
        if (automaticMovementDeactivation && ThirdPersonController.main != null) {
            Action a1 = new Action(this);
            a1.type = Action.types.enable_movement;
            a1.boolValue1 = true;
            a1.Execute();
        }
    }

    bool IsFacingSomeoneElse() {
        bool res = false;
        for (int i = 0; i< interactors.Count; i++) {
            if (interactors[i] != null) {
                if (interactors[i] != this) {
                    if (interactors[i].directionFactor <= this.directionFactor && interactors[i].interactable) {
                        return true;
                    }
                }
            }
            else {
                interactors.RemoveAt(i);
                i--;
            }
        }
        return res;
    }
/*
#if UNITY_EDITOR
    [MenuItem("GameObject/MGUB Event System/Interactive Trigger", false, 10)]
    static void CreateInteractiveTrigger(MenuCommand menuCommand) {
        GameObject parent = menuCommand.context as GameObject;
        if (parent != null) {
            GameObject go = new GameObject(parent.name.Replace(" ", "") + "InteractiveTrigger");
            go.AddComponent<InteractiveTrigger>();
            GameObjectUtility.SetParentAndAlign(go, parent);
            Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
            Selection.activeObject = go;
        }
    }
#endif
*/
}
