using System;
using Intrepid.GameManagers;
using Intrepid.Gameplay.Codex.Visual.Events;
using Intrepid.Utilities;
using Sirenix.OdinInspector;
using UnityEngine;

namespace Intrepid.Gameplay.Codex.Visual
{
    /// <summary>
    /// New visual-language entrypoint for CODEX/PDA/ActionBelt/world marks.
    /// Transitional note: this currently uses the existing Theme asset.
    /// Later Theme can be renamed/wrapped as PictorialProtocol without changing consumers much.
    /// </summary>
    public class CodexVisualService : SingletonMonoBehaviour<CodexVisualService>
    {
        [GroupConfigurations, SerializeField] private PictorialProtocolTag defaultProtocol;
        [GroupConfigurations, SerializeField] private PictorialProtocolTag currentProtocol;

        private long Version { get; set; }
        private CodexVisualContext _currentContext;

        public PictorialProtocolTag CurrentPictorialProtocol => currentProtocol.IsNull() ? defaultProtocol : currentProtocol;
        public CodexVisualContext CurrentContext
        {
            get
            {
                _currentContext ??= new CodexVisualContext(CurrentPictorialProtocol, Version);
                return _currentContext;
            }
        }

        private void Awake()
        {
            SingletonInstantiation(false, _ => { });
            _currentContext = new CodexVisualContext(CurrentPictorialProtocol, Version);
        }

        [GroupDebug, Button(ButtonSizes.Medium, ButtonStyle.FoldoutButton)]
        public void ApplyTheme(PictorialProtocolTag protocol)
        {
            if (CurrentPictorialProtocol == protocol) return;
            currentProtocol = protocol;
            _currentContext = new CodexVisualContext(CurrentPictorialProtocol, ++Version);
            Proxy.Instance.EventBus.Raise(new CodexVisualChangedEvent
            {
                Context = CurrentContext,
            });
        }
    }
}
