package su.a71.new_soviet.registration;

import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.minecraft.block.Block;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKey;
import net.minecraft.sound.SoundEvent;
import net.minecraft.util.Identifier;

import java.util.Optional;
import java.util.function.Supplier;
import su.a71.new_soviet.NewSoviet;

public class NSE_BaseRegistration {

    public static void registerItem(String name, Supplier<? extends Item> supplier, ItemGroup tab) {
        Registry.register(Registries.ITEM, new Identifier(NewSoviet.MOD_ID, name), supplier.get());

        if (tab == null) return;  // Sanity check for hidden items
        Optional<RegistryKey<ItemGroup>> key = Registries.ITEM_GROUP.getKey(tab);
        key.ifPresent(itemGroupRegistryKey -> ItemGroupEvents.modifyEntriesEvent(itemGroupRegistryKey).register(content -> {
            content.add(supplier.get());
        }));
    }

    public static void registerBlock(String name, Supplier<? extends Block> supplier, ItemGroup tab) {
        Registry.register(Registries.BLOCK, new Identifier(NewSoviet.MOD_ID, name), supplier.get());
        BlockItem blockItem = new BlockItem(supplier.get(), new FabricItemSettings());
        registerItem(name, () -> blockItem, tab);
    }

    public static SoundEvent registerSoundEvent(String name) {
        Identifier id = new Identifier(NewSoviet.MOD_ID, name);
        return Registry.register(Registries.SOUND_EVENT, id, SoundEvent.of(id));
    }

    public static <T extends BlockEntityType> T registerBlockEntity(String name, FabricBlockEntityTypeBuilder.Factory<? extends BlockEntity> factory, net.minecraft.block.Block... blocks) {
        return (T) Registry.register(
                Registries.BLOCK_ENTITY_TYPE,
                new Identifier(NewSoviet.MOD_ID, name),
                FabricBlockEntityTypeBuilder.create(factory, blocks).build());
    }

    public static void init() {}
}
