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;

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

        public override void Perform(UnitObject unit, SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            if (sourceSelect.selectObject is not ItemObject item) return;
            var container = targetSelect.containerUI.container;
            if (container.itemState.carriedBy == unit)
            {
                var otherItem = container.containerContent.items[targetSelect.slotUI.slotIndex];
                unit.unitBackpack.Drop(item);
                if (otherItem)
                {
                    container.containerContent.MoveOut(otherItem, unit);
                    unit.unitBackpack.Take(sourceSelect.slotUI.slotIndex, otherItem);
                }
                container.containerContent.MoveIn(targetSelect.slotUI.slotIndex, item, unit);
            }
            else
            {
                unit.OrderStop();
                var moveAction = new MoveAction(unit, container, unit.unitData.takeRange);
                var orderChain = new List<AbstractAction> { moveAction };
                var otherItem = container.containerContent.items[targetSelect.slotUI.slotIndex];
                if (otherItem)
                {
                    var dropAction = new DropAction(unit, item);
                    dropAction.OnBeforePerform += () => container.containerContent.MoveOut(otherItem, unit);
                    dropAction.OnAfterPerform += () => container.containerContent.MoveIn(targetSelect.slotUI.slotIndex, item, unit);
                    var takeAction = new TakeAction(unit, otherItem, sourceSelect.slotUI.slotIndex);
                    orderChain.Add(dropAction);
                    orderChain.Add(takeAction);
                }
                else
                {
                    var dropAction = new DropAction(unit, item);
                    dropAction.OnAfterPerform += () => container.containerContent.MoveIn(targetSelect.slotUI.slotIndex, item, unit);
                    orderChain.Add(dropAction);
                }
                unit.OrderChain(orderChain);
            }
        }
    }
}