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

import com.darkmagician6.eventapi.EventManager;
import com.darkmagician6.eventapi.EventTarget;
import net.minecraft.block.Blocks;
import net.minecraft.block.RespawnAnchorBlock;
import net.minecraft.item.Items;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
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;

@ModuleAnnotation(
    name = "AirAnchor",
    description = "Automatically explodes charged anchors in air",
    category = Category.CRYSTAL
)
public class AirAnchor extends Module {
    private final NumberSetting maxCount = new NumberSetting("Max Count", 1.0F, 1.0F, 10.0F, 1.0F);
    private final NumberSetting explodeSlot = new NumberSetting("Explode Slot", 1.0F, 1.0F, 9.0F, 1.0F);
    private BlockPos currentBlockPos = null;
    private int count = 0;

    public AirAnchor() {
        EventManager.register(this);
    }

    @EventTarget
    public void onUpdate(EventUpdate event) {
        if (mc.player != null && mc.world != null) {
            if (this.isEnabled()) {
                this.handleAnchorExplosion();
            } else {
                this.currentBlockPos = null;
                this.count = 0;
            }
        }
    }

    private void handleAnchorExplosion() {
        if (mc.player.getMainHandStack().getItem().equals(Items.RESPAWN_ANCHOR)) {
            if (mc.crosshairTarget instanceof BlockHitResult blockHitResult) {
                if (this.isAnchorCharged(blockHitResult.getBlockPos())) {
                    if (blockHitResult.getBlockPos().equals(this.currentBlockPos)) {
                        if ((float)this.count >= this.maxCount.getCurrent()) {
                            return;
                        }
                    } else {
                        this.currentBlockPos = blockHitResult.getBlockPos();
                        this.count = 0;
                    }

                    int explodeSlotIndex = (int)this.explodeSlot.getCurrent() - 1;
                    mc.player.getInventory().setSelectedSlot(explodeSlotIndex);
                    mc.interactionManager.interactBlock(mc.player, Hand.MAIN_HAND, blockHitResult);
                    mc.player.swingHand(Hand.MAIN_HAND);
                    this.count++;
                }
            }
        }
    }

    private boolean isAnchorCharged(BlockPos pos) {
        if (mc.world == null) {
            return false;
        } else {
            return !mc.world.getBlockState(pos).getBlock().equals(Blocks.RESPAWN_ANCHOR)
                ? false
                : (Integer)mc.world.getBlockState(pos).get(RespawnAnchorBlock.CHARGES) > 0;
        }
    }
}
