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

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