using System;
using UnityEngine;
using Logger = EscapeRoomEngine.Engine.Runtime.Utilities.Logger;
using LogType = EscapeRoomEngine.Engine.Runtime.Utilities.LogType;

namespace Station46.Modules.Laser.Scripts
{
    public enum LaserEventType
    {
        Hit, Left
    }

    public static class LaserEventExtensions
    {
        public static string Description(this LaserEventType type, LaserReceiver receiver)
        {
            var action = type switch
            {
                LaserEventType.Hit => "hit",
                LaserEventType.Left => "left",
                _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
            };

            return $"{receiver} was {action}";
        }
    }

    public delegate void LaserEventHandler(LaserReceiver source, LaserEventType e);
    
    public class LaserReceiver : MonoBehaviour
    {
        public event LaserEventHandler LaserEvent;
        
        private int _hitCount;

        /// <summary>
        /// Use this when a laser has just been pointed at this.
        /// </summary>
        public void Hit()
        {
            if (_hitCount == 0)
            {
                OnLaserEvent(LaserEventType.Hit);
            }
            _hitCount++;
        }

        /// <summary>
        /// Use this when a laser is no longer pointing at this.
        /// </summary>
        public void Leave()
        {
            if (_hitCount > 0)
            {
                _hitCount--;
            }
            if (_hitCount == 0)
            {
                OnLaserEvent(LaserEventType.Left);
            }
        }

        private void OnLaserEvent(LaserEventType type)
        {
            Logger.Log(type.Description(this), LogType.PuzzleDetail);
            
            LaserEvent?.Invoke(this, type);
        }
    }
}
