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

namespace VOID.Generic.Objects.Unit.Actions
{
    public class ForcedTakeAction : AbstractAction
    {
        private readonly UnitObject _unit;
        private readonly ItemObject _item;
        private readonly int _slotIndex;

        public ForcedTakeAction(UnitObject unit, ItemObject item)
        {
            _unit = unit;
            _item = item;
        }

        public ForcedTakeAction(UnitObject unit, ItemObject item, int slotIndex) : this(unit, item)
        {
            _slotIndex = slotIndex;
        }

        public override bool IsInRange() => true;

        protected override void OnEndIt() {}
        protected override void OnCancelIt() {}

        public override void CanDoIt()
        {
            Check(
                _unit.unitData.canTake,
                UnitActionErrorType.ThisUnitCantTake);
            Check(
                state == ActionState.Ready,
                UnitActionErrorType.ActionStateIsNotReady);
            Check(
                _item.itemData.canBePicked && _item.itemData.canBeMoved,
                UnitActionErrorType.ItemIsNotPickable);
            Check(
                !_item.itemState.carriedBy,
                UnitActionErrorType.ItemIsNotOnGround);
            Check(
                IsInRange(),
                UnitActionErrorType.NotInRange);
        }

        protected override void OnDoIt()
        {
            if (_unit.basicState.turnManager)
                _unit.unitData.UseResource(UnitResourceType.ActionPoints, 1);
            
            var pickEvent = new PickEvent
            {
                item = _item,
                unit = _unit
            };
            
            _item.itemEvents.onPickedBefore.Invoke(pickEvent);
            _unit.unitEvents.onTakeBefore.Invoke(pickEvent);

            BeforePerform();
            if (_slotIndex != default) 
                _unit.unitBackpack.Take(_slotIndex, _item);
            else
                _unit.unitBackpack.Take(_item);
            _item.itemEvents.onPickedAfter.Invoke(pickEvent);
            _unit.unitEvents.onTakeAfter.Invoke(pickEvent);
            AfterPerform();
            EndIt();
        }
    }
}