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

namespace VOID.UserInterface.Game
{
    public class OtherUnitBackpackManagerUI : MonoBehaviour
    {
        public static OtherUnitBackpackManagerUI 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.onOpenOtherUnit.RemoveListener(OnContainerOpen);
                OtherUnitBackpackUI.CurrentList.ToList().ForEach(containerUI => containerUI.Close());
            }
            _unit = unit;
            _unit.unitEvents.onOpenOtherUnit.AddListener(OnContainerOpen);
        }

        private void OnContainerOpen(OpenOtherUnitEvent openOtherUnitEvent)
        {
            Instantiate(_containerUIPrefab, gameObject.transform)
                .GetComponent<OtherUnitBackpackUI>()
                .Open(openOtherUnitEvent.otherUnit, openOtherUnitEvent.openedBy);
        }
    }
}
