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

namespace VOID.Generic.Objects.Unit.Actions
{
    public class CloseOtherUnitAction : AbstractAction
    {
        private readonly UnitObject _unit;
        private readonly UnitObject _otherUnit;
        
        public CloseOtherUnitAction(UnitObject unit, UnitObject otherUnit)
        {
            _unit = unit;
            _otherUnit = otherUnit;
        }

        public override bool IsInRange() => true;

        protected override void OnEndIt() {}

        protected override void OnCancelIt() {}

        public override void CanDoIt()
        {
            Check(
                _otherUnit.unitState.openedBy.Contains(_unit),
                UnitActionErrorType.OtherUnitIsNotOpenedByThisUnit);
        }

        protected override void OnDoIt()
        {
            var closeOtherUnitEvent = new CloseOtherUnitEvent()
            {
                closedBy = _unit,
                otherUnit = _otherUnit
            };

            BeforePerform();
            _otherUnit.unitEvents.onClosedByOtherUnit.Invoke(closeOtherUnitEvent);
            _unit.unitEvents.onCloseOtherUnit.Invoke(closeOtherUnitEvent);
            AfterPerform();
            EndIt();
        }
    }
}