using VOID.Generic.Objects.Container;
using VOID.Generic.Objects.Container.Events;
using VOID.Generic.Objects.Unit.Actions.Exceptions;

namespace VOID.Generic.Objects.Unit.Actions
{
    public class CloseContainerAction : AbstractAction
    {
        private readonly UnitObject _unit;
        private readonly ContainerObject _container;
        
        public CloseContainerAction(UnitObject unit, ContainerObject container)
        {
            _unit = unit;
            _container = container;
        }

        public override bool IsInRange() => true;
        public override bool CanSkipQueue() => true;

        protected override void OnEndIt() {}

        protected override void OnCancelIt() {}

        public override void CanDoIt()
        {
            Check(
                _container.containerState.openedBy.Contains(_unit),
                UnitActionErrorType.ContainerIsNotOpenedByThisUnit);
        }

        protected override void OnDoIt()
        {
            var containerCloseEvent = new ContainerCloseEvent
            {
                closedBy = _unit,
                container = _container
            };

            BeforePerform();
            _container.containerEvents.onClose.Invoke(containerCloseEvent);
            _unit.unitEvents.onContainerClose.Invoke(containerCloseEvent);
            AfterPerform();
            EndIt();
        }
    }
}