use crate::{generation::proto_chunk::GenerationCache, world::WorldPortalExt};
use pumpkin_data::{BlockDirection, tag};
use pumpkin_util::{
    math::position::BlockPos,
    random::{RandomGenerator, RandomImpl},
};

use super::CoralFeature;

pub struct CoralTreeFeature;

impl CoralTreeFeature {
    #[allow(clippy::too_many_arguments)]
    pub fn generate<T: GenerationCache>(
        chunk: &mut T,
        block_registry: &dyn WorldPortalExt,
        _min_y: i8,
        _height: u16,
        _feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
        random: &mut RandomGenerator,
        pos: BlockPos,
    ) -> bool {
        // First lets get a random coral
        let block = CoralFeature::get_random_tag_entry(tag::Block::MINECRAFT_CORAL_BLOCKS, random);
        let mut pos = pos;
        let i = random.next_bounded_i32(3) + 1;
        for _ in 0..i {
            if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
                return true;
            }
            pos = pos.up();
        }
        let i = random.next_bounded_i32(3) + 2;

        // TODO: Shuffle
        let directions = BlockDirection::horizontal().into_iter().take(i as usize);
        for dir in directions {
            pos = pos.offset(dir.to_offset());
            let times = random.next_bounded_i32(5) + 2;
            let mut m = 0;
            for n in 0..times {
                if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
                    break;
                }
                pos = pos.up();
                m += 1;
                if n != 0 && (m < 2 || random.next_f32() >= 0.25) {
                    continue;
                }
                pos = pos.offset(dir.to_offset());
                m = 0;
            }
        }
        true
    }
}
