﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

//This also requires that the player has a collider and rigidbody to activate the trigger
//It is set up assuming the MainCamera has a kinematic rigidbody

[HelpURL("https://docs.cognitive3d.com/unity/customevents#trigger-areas/")]
public class Cognitve3DArea : MonoBehaviour
{
    /// <summary>
    /// The name for this trigger area. Used in the Custom Event category
    /// </summary>
	public string AreaName;

    /// <summary>
    /// Only include colliders with this tag as the 'player'
    /// </summary>
    public string playerTag = "MainCamera";

    /// <summary>
    /// Send a Custom Event (using the AreaName in the Category) when the player enters this trigger
    /// </summary>
    public bool SendEnterEvent = true;
    /// <summary>
    /// Send a Custom Event (using the AreaName in the Category) when the player leaves this trigger. Automatically includes Duration as a property
    /// </summary>
    public bool SendExitEvent = true;

    CognitiveVR.CustomEvent exitEvent;

    void OnTriggerEnter(Collider collider)
    {
        if (!collider.CompareTag(playerTag)) { return; }
        if (string.IsNullOrEmpty(AreaName)) { Debug.Log("AreaName on Cognitive3D Area is empty!", this); return; }

        if (SendEnterEvent)
        {
            new CognitiveVR.CustomEvent("Enter Area " + AreaName).Send();
        }
        if (SendExitEvent)
        {
            exitEvent = new CognitiveVR.CustomEvent("Exit Area " + AreaName);
        }
    }

    void OnTriggerExit(Collider collider)
    {
        if (!collider.CompareTag(playerTag)) { return; }
        if (exitEvent != null)
        {
            exitEvent.Send();
            exitEvent = null;
        }
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(Cognitve3DArea))]
public class Cognitive3DAreaInspector : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        var area = target as Cognitve3DArea;
        var collider = area.GetComponent<Collider>();
        if (collider != null)
        {
            if (!collider.isTrigger)
            {
                EditorGUILayout.HelpBox("Collider is not trigger", MessageType.Error);
            }
        }
        else
        {
            EditorGUILayout.HelpBox("Needs a Collider", MessageType.Error);
        }

        if (string.IsNullOrEmpty(area.AreaName))
        {
            EditorGUILayout.HelpBox("Area Name is empty", MessageType.Error);
        }
    }
}
#endif