﻿//----------------------------------------------------------------------------------
// GVRNavi | Garpix Virtual Reality Navigation
// Copyright (c) 2017 Garpix Ltd.
//
// Plugin Homepage: https://gvrnavi.garpix.com
// Author Homepage: https://garpix.com
// Support: support@garpix.com
// License: Asset Store Terms of Service and EULA
// License URI: See LICENSE file in the project root for full license information.
//----------------------------------------------------------------------------------

using UnityEngine;

namespace GVRNavi
{
    public class VRObjectGaze : MonoBehaviour, IGvrGazeResponder
    {
        #region variables

        public VRObjectEvent OnGazeEnterEvent, OnGazeExitEvent, OnGazeTriggerEvent;
        public float timeToTrigger = 1f;

        public new BoxCollider collider
        {
            get
            {
                if (_collider == null)
                    _collider = GetComponent<BoxCollider>();
                return _collider;
            }
        }

        protected BoxCollider _collider;
        protected IVRContainer _parentContainer;

        #endregion


        protected virtual void Start()
        {
            UpdateParentVRContainer();
        }

        protected virtual void OnDestroy()
        {
            if (_parentContainer != null)
                _parentContainer.UnsubscribeChild(this);
        }

        #region IGvrGazeResponder

        public virtual void OnGazeEnter()
        {
            if (OnGazeEnterEvent != null)
                OnGazeEnterEvent.Invoke(this);
        }

        public virtual void OnGazeExit()
        {
            if (OnGazeExitEvent != null)
                OnGazeExitEvent.Invoke(this);
        }

        public virtual void OnGazeTrigger()
        {
            if (OnGazeTriggerEvent != null)
                OnGazeTriggerEvent.Invoke(this);
        }

        #endregion

        public static IVRContainer FindParentVRContainer(Transform t)
        {
            if (t != null)
                if (t.parent != null)
                {
                    IVRContainer c = t.parent.GetComponent<IVRContainer>();
                    if (c != null)
                        return c;
                    return FindParentVRContainer(t.parent);
                }
            return null;
        }

        public virtual void UpdateParentVRContainer()
        {
            IVRContainer c = FindParentVRContainer(transform);
            if (c != _parentContainer)
            {
                if (_parentContainer != null)
                    _parentContainer.UnsubscribeChild(this);
                _parentContainer = c;
                if (_parentContainer != null)
                    _parentContainer.SubscribeChild(this);
            }
        }

        public virtual void SetColliderEnable(bool b)
        {
            if (collider != null)
                collider.enabled = b;
        }
    }
}