using Sirenix.Utilities;
using System;
using System.Collections.Generic;
using VOID.Generic.Objects.Container;
using VOID.Generic.Objects.Container.Events;
using VOID.Generic.Objects.Item.Events;
using VOID.Generic.Objects.Unit;

namespace VOID.Generic.Objects.Item
{
    [Serializable]
    public class ContainerObjectState : ObjectComponent<ContainerObject>
    {
        #region Initialize

        protected override void EventInitialize()
        {
            parent.containerEvents.onOpen.AddListener(OnOpen);
            parent.containerEvents.onClose.AddListener(OnClose);
            parent.itemEvents.onPickedAfter.AddListener(OnPick);
        }

        #endregion

        public List<UnitObject> openedBy { get; private set; } = new();

        private void OnOpen(ContainerOpenEvent containerOpenEvent)
        {
            openedBy.Add(containerOpenEvent.openedBy);
        }

        private void OnClose(ContainerCloseEvent containerCloseEvent)
        {
            openedBy.Remove(containerCloseEvent.closedBy);
        }

        private void OnPick(PickEvent pickEvent)
        {
            Array.FindAll(parent.containerContent.items, item => item != null).ForEach(item =>
            {
                var itemPickEvent = new PickEvent
                {
                    item = item,
                    unit = pickEvent.unit
                };

                item.itemEvents.onPickedAfter.Invoke(itemPickEvent);
            });
        }
    }
}
