package com.thebrokenrail.twine.mixin;

import com.thebrokenrail.twine.item.BackpackItem;
import com.thebrokenrail.twine.util.backpack.inventory.BackpackInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.slot.Slot;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

@Mixin(Slot.class)
public class MixinSlot {
    @Shadow
    @Final
    public Inventory inventory;

    @Inject(at = @At("HEAD"), method = "canInsert", cancellable = true)
    public void canInsert(ItemStack stack, CallbackInfoReturnable<Boolean> info) {
        if (inventory instanceof BackpackInventory) {
            if (stack.getItem() instanceof BackpackItem) {
                info.setReturnValue(false);
                return;
            }
            for (int i = 0; i < inventory.size(); i++) {
                ItemStack item = inventory.getStack(i);
                if (item != ItemStack.EMPTY && (item.getItem() != stack.getItem() && (item.getMaxCount() != 1 || stack.getMaxCount() != 1))) {
                    info.setReturnValue(false);
                    return;
                }
            }
        }
    }
}
