using System; using System.Collections; using System.Collections.Generic; using System.Linq; using BITFALL.Entities.Inventory; using BITFALL.Items; using BITKit; using BITKit.Entities; using BITKit.Selection; using UnityEngine; namespace BITFALL.Player.Inventory { [CustomType(typeof(IEntitySwapItem))] public class PlayerInventorySwap : EntityBehavior,IEntitySwapItem { public bool TryGetCurrentContainer(out IBasicItemContainer container) { container = _currentContainer; return container is not null; } public event Func OpenSwapFactory; public event Action OnSwapOpened; public event Action OnSwapClosed; [Inject] private ISelector _selector; [Inject] private IHealth _health; [Inject] private IEntityInventory _inventory; private IBasicItemContainer _currentContainer; public override void OnStart() { base.OnStart(); _selector.OnActive += OnActive; _health.OnSetAlive += OnSetAlive; Data.AddListener(OnTrade); Data.AddListener(OnSwapCommand); } private void OnSwapCommand(PlayerSwapWithContainer obj) { Open(obj.Container); } private void OnTrade(PlayerTradeWithTrader obj) { } public override void OnDestroyComponent() { Data.RemoveListender(OnSwapCommand); Data.RemoveListender(OnTrade); } private void OnSetAlive(bool obj) { if (obj is false) { Close(); } } private void OnActive(ISelectable obj) { if (_currentContainer is not null) return; if (obj.Transform.TryGetComponent(out var container) is false) return; Open(container); } public bool Add(IBasicItem item) { if (_currentContainer is null) return false; return _inventory.Add(item) && _currentContainer.Remove(item); } public bool Remove(IBasicItem item) { if (_currentContainer is null) return false; return _currentContainer.Add(item) && _inventory.Remove(item); } public bool Open(IBasicItemContainer container) { if (_currentContainer is not null) return false; if (OpenSwapFactory.CastAsFunc().Any(x=>x.Invoke(container) is false)) return false; _currentContainer = container; OnSwapOpened?.Invoke(_currentContainer); container.AddHandle(GetInstanceID()); return true; } public bool Close() { if (_currentContainer is null) return false; OnSwapClosed?.Invoke(_currentContainer); _currentContainer.RemoveHandle(GetInstanceID()); _currentContainer = null; return true; } } }