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()
        {
            foreach (var language in LanguageManager.Instance.AvailableLanguages)
            {
                var newFlag = GameObject.Instantiate(FlagPrefab, FlagContainer.transform);

                var image = newFlag.GetComponentInChildren<Image>();
                string path = language.FlagImagePath;
                string name = language.Name;

                if (File.Exists(path))
                {
                    var bytes = File.ReadAllBytes(path);
                    Texture2D texture = new Texture2D(4, 4, TextureFormat.RGBA32, false);
                    texture.LoadImage(bytes);
                    Sprite sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
                        new Vector2(0.5f, 0.5f));
                    image.sprite = sp;
                    image.preserveAspect = true;
                }

                newFlag.GetComponentInChildren<TextMeshProUGUI>().SetText(name);

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

                newFlag.SetActive(true);
            }
        }

        public void SwitchLanguage(string languageCode)
        {
            Debug.Log("Switching Language to  '" + languageCode + "'");
            LanguageManager.Instance.CurrentLanguageKey = languageCode;

            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();
            }
        }
    }
}