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

        public override void Perform(UnitObject unit, SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            if (sourceSelect.selectObject is not ItemObject item) return;
            var otherUnit = item.itemState.carriedBy;
            var fromIndex = sourceSelect.slotUI.slotIndex;
            var toIndex = targetSelect.slotUI.slotIndex;
            var otherWearable = unit.unitEquipment.GetEquipped(toIndex);
            
            unit.OrderStop();
            var orderChain = new List<AbstractAction>();
            orderChain.Add(new MoveAction(unit, otherUnit, unit.unitData.takeRange));
            orderChain.Add(new TakeAction(unit, item));
            
            if (otherWearable)
            {
                var dropAction = new DropAction(unit, otherWearable);
                dropAction.OnAfterPerform += () => new ForcedTakeAction(otherUnit, item, fromIndex).DoIt();
                orderChain.Add(dropAction);
            }

            if (item is WearableObject wearable)
            {
                orderChain.Add(new EquipAction(unit, wearable, targetSelect.slotUI.slotIndex));
            }
            
            unit.OrderChain(orderChain);
        }
    }
}