using System.Linq;
using Sirenix.OdinInspector;
using UnityEngine;
using VOID.Generic.Objects.Container.Events;
using VOID.Generic.Objects.Unit;
using VOID.Generic.Player;

namespace VOID.UserInterface.Game
{
    public class ContainerManagerUI : MonoBehaviour
    {
        public static ContainerManagerUI current { get; private set; }
        
        // References
        private PlayerController _playerController;

        // Template
        [SerializeField, AssetsOnly] private GameObject _containerUIPrefab;
        
        // Unit which we listen for opening container
        private UnitObject _unit;
        
        private void Awake()
        {
            current = this;
        }

        private void Start()
        {
            _playerController = PlayerController.current;
            _playerController.OnActiveUnitChange += OnActiveUnitChange;
        }

        private void OnActiveUnitChange(UnitObject unit)
        {
            if (_unit)
            {
                _unit.unitEvents.onContainerOpen.RemoveListener(OnContainerOpen);
                ContainerUI.currentList.ToList().ForEach(containerUI => containerUI.Close());
            }
            _unit = unit;
            _unit.unitEvents.onContainerOpen.AddListener(OnContainerOpen);
        }

        private void OnContainerOpen(ContainerOpenEvent containerOpenEvent)
        {
            Instantiate(_containerUIPrefab, gameObject.transform)
                .GetComponent<ContainerUI>()
                .Open(containerOpenEvent.container, containerOpenEvent.openedBy);
        }
    }
}
