package asm.mixins;

import dev.crucifixbeta.CrucifixBeta;
import dev.crucifixbeta.api.utils.Wrapper;
import dev.crucifixbeta.api.utils.combat.CombatUtil;
import dev.crucifixbeta.mod.modules.impl.client.ClientSetting;
import dev.crucifixbeta.mod.modules.impl.combat.SelfTrap;
import dev.crucifixbeta.mod.modules.impl.player.InteractTweaks;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.WorldChunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

@Environment(EnvType.CLIENT)
@Mixin({World.class})
public abstract class MixinWorld {
   @Inject(
      method = {"getBlockState"},
      at = {@At("HEAD")},
      cancellable = true
   )
   public void blockStateHook(BlockPos pos, CallbackInfoReturnable<BlockState> cir) {
      if (Wrapper.mc.world != null && Wrapper.mc.world.isInBuildLimit(pos)) {
         if (SelfTrap.airList.contains(pos)) {
            cir.setReturnValue(Blocks.AIR.getDefaultState());
            return;
         }

         if (!ClientSetting.INSTANCE.mioCompatible.getValue()) {
            boolean var3 = CombatUtil.terrainIgnore;
            BlockPos var4 = CombatUtil.modifyPos;
            BlockState var5 = CombatUtil.modifyBlockState;
            if (var3 || var4 != null) {
               WorldChunk var6 = Wrapper.mc.world.getChunk(pos.getX() >> 4, pos.getZ() >> 4);
               BlockState var7 = var6.getBlockState(pos);
               if (var4 != null && var5 != null && pos.equals(var4)) {
                  cir.setReturnValue(var5);
                  return;
               }

               if (var3) {
                  if (CrucifixBeta.HOLE.isHard(var7.getBlock())) {
                     return;
                  }

                  cir.setReturnValue(Blocks.AIR.getDefaultState());
               }
            } else if (InteractTweaks.INSTANCE.isActive
               && Wrapper.mc.world.getChunk(pos.getX() >> 4, pos.getZ() >> 4).getBlockState(pos).getBlock() == Blocks.BEDROCK) {
               cir.setReturnValue(Blocks.AIR.getDefaultState());
            }
         }
      }
   }
}
