package net.halbear.aotg.custom.WorldGen.GenerationFeatures;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.halbear.aotg.registries.ModFoliagePlacers;
import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource;
import net.minecraft.util.valueproviders.IntProvider;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration;
import net.minecraft.world.level.levelgen.feature.foliageplacers.FoliagePlacer;
import net.minecraft.world.level.levelgen.feature.foliageplacers.FoliagePlacerType;

public class PineTreeFoliagePlacer extends FoliagePlacer {

    public static final MapCodec<PineTreeFoliagePlacer> CODEC = RecordCodecBuilder.mapCodec(instance ->
            foliagePlacerParts(instance).apply(instance, PineTreeFoliagePlacer::new)
    );

    public PineTreeFoliagePlacer(IntProvider radius, IntProvider offset) {
        super(radius, offset);
    }

    @Override
    protected FoliagePlacerType<?> type() {
        return ModFoliagePlacers.PINE_LEAVES_FOLIAGE_PLACER.get();
    }

    @Override
    protected void createFoliage(WorldGenLevel worldGenLevel, FoliageSetter foliageSetter, RandomSource randomSource, TreeConfiguration treeConfiguration, int i, FoliageAttachment foliageAttachment, int foliageHeight, int radius, int offset) {
        BlockPos center = foliageAttachment.pos().above(offset);
        radius += foliageAttachment.radiusOffset();
        for (int y = -1; y <= 1; y++) {
            for (int x = -radius; x <= radius; x++) {
                for (int z = -radius; z <= radius; z++) {
                    if(y == -1 && randomSource.nextFloat() < 0.45 || randomSource.nextFloat() < 0.85 && isPointInCircle(x,z,0,0,radius - 1)) tryPlaceLeaf(worldGenLevel, foliageSetter, randomSource, treeConfiguration, center.offset(x, y, z));
                }
            }
            radius = Math.clamp(radius - 1, 1,radius);
        }

    }

    public static boolean isPointInCircle(double pointX, double pointY, double circleX, double circleY, double radius) {
        double deltaX = pointX - circleX;
        double deltaY = pointY - circleY;
        double squaredDistance = (deltaX * deltaX) + (deltaY * deltaY);
        double squaredRadius = radius * radius;
        return squaredDistance <= squaredRadius;
    }


    @Override
    public int foliageHeight(RandomSource random, int height, TreeConfiguration config) {
        return 0;
    }

    @Override
    protected boolean shouldSkipLocation(RandomSource random, int localX, int localY, int localZ, int range, boolean large) {
        return false;
    }
}
