using UnityEngine;
using UnityEngine.UIElements;
using VOID.Generic.Objects.Unit;
using VOID.Generic.Player;

namespace VOID.UserInterface.Game.Party
{
    public class PartyUI : MonoBehaviour
    {
        public static PartyUI current { get; private set; }
        
        // Visual Elements
        private VisualElement _rootElement;

        private PartyUnitUI _partyMainUnit;
        private PartyUnitUI _partySubUnit;

        private void Awake()
        {
            current = this;
            
            var uiDocument = gameObject.GetComponent<UIDocument>();
            var templateElement = uiDocument.rootVisualElement;

            _rootElement = templateElement.Q("root-party");
            
            // Find all important elements + initialize MainUnit element
            _partyMainUnit = gameObject.AddComponent<PartyUnitUI>();
            _partyMainUnit.Init(templateElement.Q("main-unit"));

            // Find all important elements + initialize SubUnit element
            _partySubUnit = gameObject.AddComponent<PartyUnitUI>();
            _partySubUnit.Init(templateElement.Q("sub-unit"));
            
            _rootElement.dataSource = this;
            _rootElement.pickingMode = PickingMode.Position;
        }

        private void Start()
        {
            // This will set portrait active (highlight border) if it belong to currently active unit
            PlayerController.current.OnActiveUnitChange += OnActiveUnitChange;
            
            // Updating portraits of party unit when they change
            PlayerController.current.OnMainUnitChange += OnMainUnitChange;
            PlayerController.current.OnSubUnitChange += OnSubUnitChange;
        }

        private void OnActiveUnitChange(UnitObject unitObject)
        {
            _partyMainUnit.SetActive(_partyMainUnit.unit == unitObject);
            _partySubUnit.SetActive(_partySubUnit.unit == unitObject);
        }

        private void OnMainUnitChange(UnitObject unitObject)
        {
            _partyMainUnit.SetUnit(unitObject);
        }

        private void OnSubUnitChange(UnitObject unitObject)
        {
            _partySubUnit.SetUnit(unitObject);
        }
    }
}
