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

namespace RothenburgAR.UI
{
    public class LanguageSelectViewBehaviour : BaseViewBehaviour
    {
        [SerializeField] private GameObject FlagContainer;
        [SerializeField] private GameObject FlagPrefab;

        public void Start()
        {
            CreateLanguageSelectionFlags();
        }

        private void CreateLanguageSelectionFlags()
        {
            foreach (var language in LanguageManager.Instance.AvailableLanguages)
            {
                var newFlag = InstantiateFlag(language);

                newFlag.GetComponentInChildren<Button>().onClick.AddListener(() => { SwitchLanguage(language.Key); });
            }
        }

        private GameObject InstantiateFlag(LanguageDescription language)
        {
            var newFlag = GameObject.Instantiate(FlagPrefab, FlagContainer.transform);
            newFlag.SetActive(true);

            var texture = Resources.Load<Texture2D>(language.FlagImagePath);
            if (texture != null)
            {
                var image = newFlag.GetComponentInChildren<Image>();
                image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                image.preserveAspect = true;
            }

            newFlag.GetComponentInChildren<TextMeshProUGUI>().SetText(language.Name);

            return newFlag;
        }

        public void SwitchLanguage(string languageCode)
        {
            Debug.Log("Switching Language to  '" + languageCode + "'");
            LanguageManager.Instance.CurrentLanguageKey = languageCode;
            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) SwitchToColorSelectView();
            else SwitchToARView();
        }
    }
}