using System;
using UnityEngine.UIElements;
using VOID.ScriptableObjects;

namespace VOID.UserInterface.Game.Util
{
    [Serializable]
    public class StatusUI
    {
        // Content of slot
        public BasicStatus status { get; private set; }
        
        // Elements
        private VisualElement _templateElement;
        private VisualElement _iconElement;
        private Label _timerLabel;

        /// <summary>
        /// Initializes completly new <see cref="StatusUI"/> inside given parent.
        /// </summary>
        /// <param name="parentWrapperElement">Create new status as child in given parent.</param>
        /// <param name="status"><see cref="BasicStatus"/> to use for this StatusUI</param>
        /// <param name="name">Optional name for UI element</param>
        public void InitNew(VisualElement parentWrapperElement, BasicStatus status, string name = null)
        {
            this.status = status;
            
            // Create Status (from template) in GUI
            _templateElement = GameUI.current.statusTemplate.CloneTree().contentContainer;
            _templateElement.name = name ?? "status";
            _templateElement.AddToClassList("status");
            _templateElement.AddToClassList("status-medium");
            parentWrapperElement.Add(_templateElement);
            
            // Find all Status's elements
            _iconElement = _templateElement.Q("icon");
            _iconElement.style.backgroundImage = new StyleBackground(status.displayIcon);
            _timerLabel = _templateElement.Q<Label>("time-remaining");
            
            // Monitor what happening to displayed status
            status.OnTimeDecrease += OnTimeDecrease;
            
            // Also force
            OnTimeDecrease();

            _templateElement.dataSource = this;
            _templateElement.pickingMode = PickingMode.Position;
        }

        public void Destroy()
        {
            status.OnTimeDecrease -= OnTimeDecrease;
            _templateElement.parent.Remove(_templateElement);
        }

        private void OnTimeDecrease()
        {
            _timerLabel.text = status.durationLeft.ToString("0");
        }
    }
}