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

namespace RothenburgAR.UI
{
    public class ReticuleBehaviour : MonoBehaviour
    {
        private Animator _animator;
        private Animator _poiAnimator;

        void Start()
        {
            _animator = GetComponent<Animator>();
        }

        // Update is called once per frame
        void Update()
        {
            var hitInfo = SendRay();
            ProcessHitInfo(hitInfo);
        }

        private void ProcessHitInfo(RaycastHit hitInfo)
        {
            if (hitInfo.transform == null || hitInfo.transform.gameObject.GetComponent<PoiRaycastReceiverBehaviour>() == null)
            {
                _animator.SetBool("CanTriggerPoi", false);
                if (_poiAnimator != null)
                {
                    _poiAnimator.SetBool("IsHighlighted", false);
                }
                return;
            }

            GameObject go = hitInfo.transform.gameObject;
            var bb = go.GetComponent<PoiRaycastReceiverBehaviour>();

            if (bb == null) return;

            _animator.SetBool("CanTriggerPoi", true);

            if (_poiAnimator != null)
            {
                _poiAnimator.SetBool("IsHighlighted", false);
            }
            _poiAnimator = bb.transform.GetComponentInParent<Animator>();
            _poiAnimator.SetBool("IsHighlighted", true);

        }

        private static RaycastHit SendRay()
        {
            Vector2 center = new Vector2(Camera.main.pixelWidth / 2, Camera.main.pixelHeight / 2);
            Ray r = Camera.main.ScreenPointToRay(center);

            RaycastHit hitInfo = new RaycastHit();
            Physics.Raycast(r, out hitInfo);
            Debug.DrawRay(r.origin, r.direction, Color.magenta, 10f);
            return hitInfo;
        }
    }
}