package net.yyc12345.teyvatcraft.mixin;

import java.util.List;
import java.util.Random;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.At;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.GrassBlock;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.WorldView;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.FlowerFeature;

// due to minecraft shit design, the bone meal only can grow grass block's first flowerFeature
// this mixin class is designed to fix this shitty design.

@Mixin(GrassBlock.class)
public class GrassBlockFixer {
    @Inject(method = "grow", at = @At("HEAD"))
    public void grow(ServerWorld world, Random random, BlockPos pos, BlockState state, CallbackInfo ci) {
        BlockPos blockPos = pos.up();
        BlockState blockState = Blocks.GRASS.getDefaultState();
        int i;
        label32: for (i = 0; i < 128; i++) {
            BlockState blockState4;
            BlockPos blockPos2 = blockPos;
            // random walk
            for (int j = 0; j < i / 16; ) {
                blockPos2 = blockPos2.add(random.nextInt(3) - 1, (random.nextInt(3) - 1) * random.nextInt(3) / 2, random.nextInt(3) - 1);
                if (world.getBlockState(blockPos2.down()).isOf(world.getBlockState(pos).getBlock()/* this */)) {
                    if (world.getBlockState(blockPos2).isFullCube((BlockView)world, blockPos2))
                        continue label32; 
                    j++;
                } 
                continue label32;
            }

            // try place flower
            if (random.nextInt(8) == 0) {
                List<ConfiguredFeature<?, ?>> list = world.getBiome(blockPos2).getGenerationSettings().getFlowerFeatures();
                if (list.isEmpty())
                    continue;
                ConfiguredFeature<?, ?> configuredFeature = list.get(random.nextInt(list.size() - 1) + 1);
                FlowerFeature flowerFeature = (FlowerFeature)configuredFeature.feature;
                blockState4 = flowerFeature.getFlowerState(random, blockPos2, configuredFeature.getConfig());
            } else {
                blockState4 = blockState;
            }

            // place flower
            if (blockState4.canPlaceAt((WorldView)world, blockPos2))
                world.setBlockState(blockPos2, blockState4, 3); 
            continue;
        }
    }
}
