using RothenburgAR.Common;
using System;
using System.IO;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Vuforia;
using Image = UnityEngine.UI.Image;

namespace RothenburgAR.UI
{
    public class FontsizeSelectViewBehaviour : BaseViewBehaviour
    {
        [SerializeField] private GameObject FontsizeContainer;
        [SerializeField] private GameObject FontsizePrefab;

        public void Start()
        {
            CreateLanguageSelectionFlags();
        }

        private void CreateLanguageSelectionFlags()
        {
            foreach (FontsizeSetting setting in Enum.GetValues(typeof(FontsizeSetting)))
            {
                var newSize = Instantiate(FontsizePrefab, FontsizeContainer.transform);
                newSize.SetActive(true);

                var children = newSize.GetComponentsInChildren<TextMeshProUGUI>().ToList();
                var icon = children.FirstOrDefault(c => c.gameObject.name.Contains("Icon"));
                var text = children.FirstOrDefault(c => c.gameObject.name.Contains("Text"));

                if (icon == null || text == null)
                {
                    Destroy(newSize);
                    Debug.LogError("Could not create Fontsize Selection Buttons, Icon and Text component could not be found by name.");
                }

                icon.fontSize = FontsizeManager.Instance.GetFontsize(FontsizeClass.Header, setting);
                text.text = LanguageManager.Instance.GetString("t_languageselect_" + Enum.GetName(typeof(FontsizeSetting), setting));

                newSize.GetComponentInChildren<Button>().onClick.AddListener(() => SwitchToFontsize(setting));
            }
        }

        public void SwitchToFontsize(FontsizeSetting setting)
        {
            Debug.Log("Switching Font size to '" + Enum.GetName(typeof(FontsizeSetting), setting) + "'");
            FontsizeManager.Instance.CurrentFontsizeSetting = setting;
            if (!UIManager.Instance.StartingUp) SettingsManager.Instance.PersistSettings();

            StateManager sm = TrackerManager.Instance.GetStateManager();
            foreach (var item in sm.GetActiveTrackableBehaviours())
            {
                var teh = item.gameObject.GetComponent<TrackableEventHandler>();
                teh.OnTrackableStateChanged(TrackableBehaviour.Status.NOT_FOUND, TrackableBehaviour.Status.TRACKED);
            }

            if (UIManager.Instance.StartingUp) SwitchToTutorialView();
            else SwitchToARView();
        }
    }
}