using RothenburgAR.Exhibition;
using RothenburgAR.PointOfInterest;
using UnityEngine;
using Vuforia;

namespace RothenburgAR.UI
{
    internal class TrackableEventHandler : MonoBehaviour, ITrackableEventHandler
    {
        public ExhibitBehaviour Exhibit { get; set; }

        public void OnTrackableStateChanged(TrackableBehaviour.Status previousStatus, TrackableBehaviour.Status newStatus)
        {
            if (previousStatus == TrackableBehaviour.Status.NOT_FOUND && newStatus == TrackableBehaviour.Status.TRACKED)
            {
                // Dynamically load Title when Exhibit is found
                ExhibitTitleBehaviour titleElement = Exhibit.TitleBehaviour;
                titleElement.DisplayText = titleElement.DataText.GetTextByLanguage(LanguageManager.Instance.CurrentLanguageKey);
                titleElement.gameObject.SetActive(false);
                titleElement.gameObject.SetActive(true);
            }


            if (UIManager.Instance == null || !UIManager.Instance.IsARViewVisible) return;
            if (previousStatus == TrackableBehaviour.Status.NOT_FOUND && newStatus == TrackableBehaviour.Status.TRACKED)
            {
                // Reactivate Projection effect when the Exhibit that contains the opened POI is tracked again
                var poi = UIManager.Instance.ARViewBehaviour.ProjectionEffect.SelectedPOI;
                if (UIManager.Instance.ARViewBehaviour.DetailsPanel.gameObject.activeInHierarchy && poi != null)
                {
                    if (poi.GetComponent<PoiBehaviour>().Exhibit == Exhibit)
                    {
                        UIManager.Instance.ARViewBehaviour.ProjectionEffect.SetActive(true);
                    }
                }
            }

            // Deactivate Projection effect when the Exhibit that contains the opened POI is lost
            if (previousStatus == TrackableBehaviour.Status.TRACKED && newStatus == TrackableBehaviour.Status.NOT_FOUND)
            {
                var poi = UIManager.Instance.ARViewBehaviour.ProjectionEffect.SelectedPOI;
                if (UIManager.Instance.ARViewBehaviour.DetailsPanel.gameObject.activeInHierarchy && poi != null)
                {
                    if (poi.GetComponent<PoiBehaviour>().Exhibit == Exhibit)
                    {
                        UIManager.Instance.ARViewBehaviour.ProjectionEffect.SetActive(false);
                    }
                }
            }
        }
    }
}