using System.Collections.Generic;
using VOID.Generic.Dict;
using VOID.Generic.Objects.Item;
using VOID.Generic.Objects.Unit;
using VOID.Generic.Objects.Unit.Actions;
using VOID.Generic.Objects.Wearable;
using VOID.Generic.Player.Util;

namespace VOID.Generic.Player.DraggingOperation
{
    public class OtherUnitBackpackToBackpackDraggingOperation : AbstractDraggingOperation
    {
        public override bool Check(SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            return sourceSelect.slotUI?.slotType == SlotType.OtherUnitBackpackSlot
                   && targetSelect.slotUI?.slotType == SlotType.BackpackSlot;
        }

        public override void Perform(UnitObject unit, SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            if (sourceSelect.selectObject is not ItemObject otherItem) return;
            var otherUnit = otherItem.itemState.carriedBy;
            var thisItem = targetSelect.slotUI.item;
            
            unit.OrderStop();
            var moveAction = new MoveAction(unit, otherUnit, unit.unitData.takeRange);
            var orderChain = new List<AbstractAction> { moveAction };
            var takeAction = new TakeAction(unit, otherItem, targetSelect.slotUI.slotIndex);
            if (thisItem && otherItem.CanStackWith(thisItem))
                takeAction.OnAfterPerform += () => otherItem.StackWith(thisItem);
            orderChain.Add(takeAction);
            unit.OrderChain(orderChain);
        }
    }
}