﻿using JLGames.RocketDriver.Actions.Extensions;
using JLGames.RocketDriver.Actions.i18n;
using UnityEngine;
using UnityEngine.UIElements;

namespace JLGames.RocketDriver.Editor.Windows.GettingStarted
{
    internal class SectionElement
    {
        private readonly Label m_Title;
        private readonly Label m_Content;
        private readonly Button m_Button1;
        private readonly Button m_Button2;
        private SectionI18NValues m_Values;

        public Label Title => m_Title;
        public Label Content => m_Content;
        public Button Button1 => m_Button1;
        public Button Button2 => m_Button2;

        public SectionElement(VisualElement sectionNode)
        {
            m_Title = sectionNode.GetElementByChain<Label>("container/labels/title");
            m_Content = sectionNode.GetElementByChain<Label>("container/labels/content");
            m_Button1 = sectionNode.GetElementByChain<Button>("container/buttons/btn0");
            m_Button2 = sectionNode.GetElementByChain<Button>("container/buttons/btn1");
        }

        public void UpdateValues(II18NManager i18NManager, string baseNodePath)
        {
            if (null == m_Title || null == i18NManager) return;
            m_Values = new SectionI18NValues();
            m_Values.UpdateValues(i18NManager, baseNodePath);
            m_Title.text = i18NManager.GetValue($"{baseNodePath}.title");
            m_Content.text = i18NManager.GetValue($"{baseNodePath}.content");
            m_Button1.text = i18NManager.GetValue($"{baseNodePath}.button1");
            m_Button2.text = i18NManager.GetValue($"{baseNodePath}.button2");
        }

        public void RegisterButtonsCallback()
        {
            m_Button1.RegisterCallback<MouseUpEvent, string>(OnClickButton1, m_Button1.viewDataKey);
            m_Button2.RegisterCallback<MouseUpEvent, string>(OnClickButton2, m_Button2.viewDataKey);
        }

        public void UnregisterButtonsCallback()
        {
            m_Button2.UnregisterCallback<MouseUpEvent, string>(OnClickButton2);
            m_Button1.UnregisterCallback<MouseUpEvent, string>(OnClickButton1);
        }

        private void OnClickButton1(MouseUpEvent evt, string data)
        {
            OpenUrl(m_Values.Page1);
        }

        private void OnClickButton2(MouseUpEvent evt, string data)
        {
            OpenUrl(m_Values.Page2);
        }

        private void OpenUrl(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                Application.OpenURL(url);
            }
        }
    }
}