using VOID.Generic.Dict;
using VOID.Generic.Objects.Unit;
using VOID.Generic.Objects.Unit.Actions;
using VOID.Generic.Objects.Wearable;
using VOID.Generic.Player.Util;
using VOID.UserInterface;
using VOID.UserInterface.Game;

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

        public override void Perform(UnitObject unit, SelectUtilResult sourceSelect, SelectUtilResult targetSelect)
        {
            if (sourceSelect.selectObject is not WearableObject wearable) return;
            unit.OrderStop();
            var container = targetSelect.containerUI.container;
            if (container.itemState.carriedBy == unit)
            {
                var unEquipAction = new UnEquipAction(unit, wearable);
                unEquipAction.OnAfterPerform += () =>
                    container.containerContent.MoveIn(targetSelect.slotUI.slotIndex, wearable, unit);
                unit.Order(unEquipAction);
            }
            else
            {
                unit.Order(new MoveAction(unit, targetSelect.position, unit.unitData.takeRange));
                var dropAction = new DropAction(unit, wearable);
                var moveItemAction = new MoveItemAction(unit, wearable, container.transform.position);
                moveItemAction.runAfterAction = dropAction;
                moveItemAction.OnAfterPerform += () =>
                    container.containerContent.MoveIn(targetSelect.slotUI.slotIndex, wearable, unit);
                unit.Order(dropAction);
                unit.Order(moveItemAction);
            }
        }
    }
}