using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;
using UnityEngine.XR.Interaction.Toolkit;

namespace _PROJECT.NewHandPresence
{
    public class XRControllerHintController : MonoBehaviour
    {
        public ControllerInformationScriptableObject controllerInformation;
        public GameObject turnControl, smoothLocomotionControl, teleportControl;
        // List due to Vive Wands having 2 grip buttons
        public List<GameObject> gripControls; 
        public Billboard billboard;
        [HideInInspector] public XRBaseController xrBaseController;

        private int _defaultLayer, _outLineLayer;
        private List<GameObject> _currentControls;

        private void Start()
        {
            _defaultLayer = LayerMask.NameToLayer("Default");
            _outLineLayer = LayerMask.NameToLayer("Outlined Objects");
            _currentControls = new List<GameObject>();
            billboard.HideHint();
        }

        private void ShowHint(GameObject control, string text)
        {
            control.layer = _outLineLayer;
            billboard.ShowHint(text);
            billboard.SetLineTarget(control);
            _currentControls.Add(control);
        }
        
        private void ShowHints(List<GameObject> controls, string text)
        {
            controls.ForEach(control => control.layer = _outLineLayer);
            billboard.ShowHint(text);
            _currentControls.AddRange(controls);
        }


        public void HideHint()
        {
            _currentControls?.ForEach(control => control.layer = _defaultLayer);
            _currentControls?.Clear();
            billboard.HideHint();
        }

        public void ShowTurnHint()
        {
            if (turnControl == null) return;
            ShowHint(turnControl, controllerInformation.turnHintText);
            VibrateController();
        }

        public void ShowSmoothLocomotionHint()
        {
            if (smoothLocomotionControl == null) return;
            ShowHint(smoothLocomotionControl, controllerInformation.moveHintText);
            VibrateController();
        }

        public void ShowTeleportHint()
        {
            if (teleportControl == null) return;
            ShowHint(teleportControl, controllerInformation.teleportStartHintText);
            VibrateController();
        }

        public void ShowGripHint()
        {
            if (gripControls.Count == 0) return;
            ShowHints(gripControls, controllerInformation.gripHintText);
            VibrateController();
        }
        
        private void VibrateController()
        {
            if (xrBaseController == null) return;
            xrBaseController.SendHapticImpulse(controllerInformation.vibrationStrength, controllerInformation.vibrationDuration);
        }
    }
}