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

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

        public override bool IsInRange()
        {
            return RangeUtil.IsInRange(_unit, _otherUnit, _unit.unitData.takeRange);
        }

        protected override void OnEndIt() {}

        protected override void OnCancelIt() {}
        
        public override void CanDoIt()
        {
            Check(
                state == ActionState.Ready,
                UnitActionErrorType.ActionStateIsNotReady);
            if (_unit.basicState.turnManager)
            {
                Check(
                    _unit.unitState.isSelfTurn,
                    UnitActionErrorType.UnitSelfTurnNotActive);
            }
            Check(
                _unit.unitState.isControllable,
                UnitActionErrorType.UnitStateIsNotControllable);
            Check(
                IsInRange(),
                UnitActionErrorType.NotInRange);
            Check(
                _otherUnit.basicState.isDead,
                UnitActionErrorType.NotInRange);
            Check(
                !_otherUnit.unitState.openedBy.Contains(_unit),
                UnitActionErrorType.OtherUnitIsAlreadyOpenedByThisUnit);
        }

        protected override void OnDoIt()
        {
            var openOtherUnitEvent = new OpenOtherUnitEvent()
            {
                openedBy = _unit,
                otherUnit = _otherUnit
            };

            _unit.OrderInstantly(new RotateAction(_unit, _otherUnit));
            
            BeforePerform();
            _otherUnit.unitEvents.onOpenedByOtherUnit.Invoke(openOtherUnitEvent);
            _unit.unitEvents.onOpenOtherUnit.Invoke(openOtherUnitEvent);
            AfterPerform();
            EndIt();
        }
    }
}