package me.deftware.mixin.mixins.world;

import me.deftware.client.framework.world.classifier.BlockClassifier;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.render.chunk.ChunkRendererRegion;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
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(ChunkRendererRegion.class)
public abstract class MixinChunkRenderRegion {

	@Shadow @Final
	protected BlockState[] blockStates;

	@Shadow
	protected abstract int getIndex(BlockPos pos);

	/*
		This function is called every time a chunk is built
	 */
	@Inject(method = "getBlockState", at = @At("HEAD"))
	private void getBlockState(BlockPos pos, CallbackInfoReturnable<BlockState> state) {
		if (blockStates != null && pos != null) {
			BlockState blockState = blockStates[getIndex(pos)];
			Block block = blockState.getBlock();
			int id = Registry.BLOCK.getRawId(block);
			BlockClassifier.getClassifiers().forEach(blockClassifier -> blockClassifier.classify(block, pos, id));
		}
	}

}

@@ -357,25 +357,118 @@
 til.
-registry.Registry
+math.ChunkSectionPos;%0Aimport net.minecraft.util.registry.Registry;%0Aimport net.minecraft.world.chunk.WorldChunk
 ;%0Aim
@@ -863,17 +863,18 @@
 %09@Shadow
- 
+%0A%09
 @Final%0A%09
@@ -887,32 +887,24 @@
 ted 
-BlockState%5B%5D blockStates
+int chunkZOffset
 ;%0A%0A%09
@@ -911,16 +911,24 @@
 @Shadow%0A
+%09@Final%0A
 %09protect
@@ -934,43 +934,76 @@
 ted 
-abstract int getIndex(BlockPos pos)
+int chunkXOffset;%0A%0A%09@Shadow%0A%09@Final%0A%09protected WorldChunk%5B%5D%5B%5D chunks
 ;%0A%0A%09
@@ -1060,17 +1060,16 @@
  built%0A%09
- 
 */%0A%09@Inj
@@ -1212,101 +1212,270 @@
 if (
-blockStates != null && pos != null) %7B%0A%09%09%09BlockState blockState = blockStates%5BgetIndex
+pos != null) %7B%0A%09%09%09int i = ChunkSectionPos.getSectionCoord(pos.getX()) - this.chunkXOffset;%0A%09%09%09int j = ChunkSectionPos.getSectionCoord(pos.getZ()) - this.chunkZOffset;%0A%09%09%09BlockState blockState = this.chunks%5Bi%5D%5Bj%5D.getBlockState
 (pos)
-%5D
 ;%0A
+%09%09%09if (blockState != null) %7B%0A%09
 %09%09%09B
@@ -1510,16 +1510,17 @@
 lock();%0A
+%09
 %09%09%09int i
@@ -1555,16 +1555,17 @@
 block);%0A
+%09
 %09%09%09Block
@@ -1662,16 +1662,21 @@
 , id));%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%0A

Fix crash