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.Player.Util;
using VOID.UserInterface;
using VOID.UserInterface.Game;

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

        public override void Perform(UnitObject unit, SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            if (sourceSelect.selectObject is not ItemObject item) return;
            var otherUnit = GameUI.current.PickComponentUI<OtherUnitBackpackUI>().unit;
            
            unit.OrderStop();
            var moveAction = new MoveAction(unit, otherUnit, unit.unitData.takeRange);
            var orderChain = new List<AbstractAction> { moveAction };
            var otherItem = otherUnit.unitBackpack.items[targetSelect.slotUI.slotIndex];
            if (otherItem)
            {
                var dropAction = new DropAction(unit, item);
                dropAction.OnAfterPerform += () => new ForcedDropAction(otherUnit, otherItem).DoIt();
                orderChain.Add(dropAction);
                var canStack = item.CanStackWith(otherItem, out var itemWillBeRemoved);
                if (canStack) dropAction.OnAfterPerform += () => item.StackWith(otherItem);
                if (!canStack || !itemWillBeRemoved)
                {
                    dropAction.OnAfterPerform += () => new ForcedTakeAction(otherUnit, item, targetSelect.slotUI.slotIndex).DoIt();
                    orderChain.Add(new TakeAction(unit, otherItem, sourceSelect.slotUI.slotIndex));
                }
            }
            else
            {
                var dropAction = new DropAction(unit, item);
                dropAction.OnAfterPerform += () => new ForcedTakeAction(otherUnit, item, targetSelect.slotUI.slotIndex).DoIt();
                orderChain.Add(dropAction);
            }
            unit.OrderChain(orderChain);
        }
    }
}