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

        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;
            if (container.itemState.carriedBy == unit)
            {
                unit.Order(new MoveAction(unit, targetSelect.position, unit.unitData.takeRange));
                var dropAction = new DropAction(unit, item);
                dropAction.OnBeforePerform += () => container.containerContent.MoveOut(item, unit);
                dropAction.OnBeforePerform += () => unit.unitBackpack.Take(item);
                var moveItemAction = new MoveItemAction(unit, item, targetSelect.position);
                moveItemAction.runAfterAction = dropAction;
                unit.Order(dropAction);
                unit.Order(moveItemAction);
            }
            else
            {
                unit.Order(new MoveAction(unit, sourceSelect.position, unit.unitData.takeRange));
                var moveItemAction = new MoveItemAction(unit, item, targetSelect.position);
                moveItemAction.OnBeforePerform += () => container.containerContent.MoveOut(item, unit);
                unit.Order(moveItemAction);
            }
        }
    }
}