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 OtherUnitBackpackToOtherUnitBackpackDraggingOperation : AbstractDraggingOperation
    {
        public override bool Check(SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            return sourceSelect.slotUI?.slotType == SlotType.OtherUnitBackpackSlot
                   && targetSelect.slotUI?.slotType == SlotType.OtherUnitBackpackSlot;
        }

        public override void Perform(UnitObject unit, SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            if (sourceSelect.selectObject is not ItemObject fromItem) return;
            unit.OrderStop();
            unit.Order(new MoveAction(unit, sourceSelect.position, unit.unitData.takeRange));
            var fromDeadUnit = fromItem.itemState.carriedBy;
            var toDeadUnit = GameUI.current.PickComponentUI<OtherUnitBackpackUI>().unit;
            var fromIndex = sourceSelect.slotUI.slotIndex;
            var toIndex = targetSelect.slotUI.slotIndex;
            var toItem = toDeadUnit.unitBackpack.items[toIndex];

            if (toItem)
            {
                var moveItemAction = new MoveItemAction(unit, fromItem, toDeadUnit.transform.position);
                moveItemAction.OnBeforePerform += () => new ForcedDropAction(fromDeadUnit, fromItem).DoIt();
                moveItemAction.OnBeforePerform += () => new ForcedDropAction(toDeadUnit, toItem).DoIt();
                var canStack = fromItem.CanStackWith(toItem, out var itemWillBeRemoved);
                if (canStack) moveItemAction.OnBeforePerform += () => fromItem.StackWith(toItem);
                moveItemAction.OnAfterPerform += () => new ForcedTakeAction(toDeadUnit, fromItem, toIndex).DoIt();
                if (!itemWillBeRemoved) moveItemAction.OnAfterPerform += () => new ForcedTakeAction(fromDeadUnit, toItem, fromIndex).DoIt();
                unit.Order(moveItemAction);
            }
            else
            {
                var moveItemAction = new MoveItemAction(unit, fromItem, toDeadUnit.transform.position);
                moveItemAction.OnBeforePerform += () => new ForcedDropAction(fromDeadUnit, fromItem).DoIt();
                moveItemAction.OnAfterPerform += () => new ForcedTakeAction(toDeadUnit, fromItem, toIndex).DoIt();
                unit.Order(moveItemAction);
            }
        }
    }
}