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

namespace Ktyl.Util
{
    public class UnseenEventTrigger : MonoBehaviour
    {
        [System.Serializable]
        private struct Event
        {
            public GameEvent game;
            public UnityEvent unity;

            public void Raise()
            {
                if (game) game.Raise();
                unity.Invoke();
            }
        }

        [SerializeField]
        private float _minDistance = 2f;

        [SerializeField]
        [Range(0f, 180f)]
        private float _minAngle = 90.0f;
        
        [SerializeField] private Event _onUnseen;
        
        private bool _isArmed = false;
        private Camera _camera;

        public void Disarm()
        {
            _isArmed = false;
        }

        public void Arm()
        {
            _isArmed = true;
        }
            
        private void Update()
        {
            if ( !_isArmed )
                return;

            if ( !IsUnseen() )
                return;
            
            _onUnseen.Raise();

            _isArmed = false;
        }

        private bool IsUnseen()
        {
            // lazy init camera
            if ( _camera == null )
            {
                _camera = Camera.main;
            }

            var camDiff = transform.position - _camera.transform.position;
            
            // distance check
            if ( camDiff.sqrMagnitude < _minDistance * _minDistance )
            {
                // too close!
                return false;
            }
            
            // angle check
            float angleDiff = Vector3.Angle( camDiff.normalized, _camera.transform.forward );
            if ( angleDiff < _minAngle )
            {
                return false;
            }
            
            return true;
        }
    }
}
