package zenith.zov.client.modules.impl.combat;

import com.darkmagician6.eventapi.EventTarget;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.screen.slot.SlotActionType;
import zenith.zov.base.events.impl.player.EventUpdate;
import zenith.zov.client.modules.api.Category;
import zenith.zov.client.modules.api.Module;
import zenith.zov.client.modules.api.ModuleAnnotation;
import zenith.zov.client.modules.api.setting.impl.NumberSetting;
import zenith.zov.utility.interfaces.IMinecraft;

@ModuleAnnotation(
    name = "AutoTotem",
    category = Category.COMBAT,
    description = "Automatically holds totem in your off hand"
)
public final class AutoTotem extends Module implements IMinecraft {
    public static final AutoTotem INSTANCE = new AutoTotem();
    private final NumberSetting delay = new NumberSetting("Delay", 1.0F, 0.0F, 5.0F, 0.1F);
    private int delayCounter;

    private AutoTotem() {
    }

    @Override
    public void onEnable() {
        super.onEnable();
    }

    @Override
    public void onDisable() {
        super.onDisable();
    }

    @EventTarget
    public void onUpdate(EventUpdate event) {
        if (mc.player != null && mc.world != null) {
            if (mc.currentScreen == null) {
                if (mc.player.getInventory().getStack(40).getItem() == Items.TOTEM_OF_UNDYING) {
                    this.delayCounter = (int)this.delay.getCurrent();
                } else if (this.delayCounter > 0) {
                    this.delayCounter--;
                } else {
                    int slot = this.findItemSlot(Items.TOTEM_OF_UNDYING);
                    if (slot != -1) {
                        mc.interactionManager.clickSlot(mc.player.currentScreenHandler.syncId, convertSlotIndex(slot), 40, SlotActionType.SWAP, mc.player);
                        this.delayCounter = (int)this.delay.getCurrent();
                    }
                }
            }
        }
    }

    private int findItemSlot(Item item) {
        if (mc.player == null) {
            return -1;
        } else {
            for (int i = 0; i < 36; i++) {
                if (mc.player.getInventory().getStack(i).isOf(item)) {
                    return i;
                }
            }

            return -1;
        }
    }

    private static int convertSlotIndex(int slotIndex) {
        return slotIndex < 9 ? 36 + slotIndex : slotIndex;
    }
}
