package net.minecraft.client.gui.screens;

import net.minecraft.client.gui.GuiComponent;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Item;
import net.minecraft.client.gui.components.AbstractSelectionList;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.world.item.Items;
import java.util.Arrays;
import net.minecraft.world.level.block.Blocks;
import org.apache.logging.log4j.LogManager;
import net.minecraft.world.level.levelgen.feature.configurations.StructureFeatureConfiguration;
import java.util.Map;
import net.minecraft.world.level.levelgen.feature.configurations.StrongholdConfiguration;
import java.util.Optional;
import net.minecraft.world.level.levelgen.StructureSettings;
import com.google.common.collect.Maps;
import net.minecraft.world.level.levelgen.feature.StructureFeature;
import net.minecraft.world.level.ItemLike;
import net.minecraft.network.chat.FormattedText;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.CommonComponents;
import java.util.Iterator;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import com.google.common.base.Splitter;
import java.util.Collections;
import com.google.common.collect.Lists;
import javax.annotation.Nullable;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.Registry;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.levelgen.flat.FlatLayerInfo;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import java.util.List;
import org.apache.logging.log4j.Logger;

public class PresetFlatWorldScreen extends Screen {
    private static final Logger LOGGER;
    private static final List<PresetInfo> PRESETS;
    private final CreateFlatWorldScreen parent;
    private Component shareText;
    private Component listText;
    private PresetsList list;
    private Button selectButton;
    private EditBox export;
    private FlatLevelGeneratorSettings settings;
    
    public PresetFlatWorldScreen(final CreateFlatWorldScreen dps) {
        super(new TranslatableComponent("createWorld.customize.presets.title"));
        this.parent = dps;
    }
    
    @Nullable
    private static FlatLayerInfo getLayerInfoFromString(final String string, final int integer) {
        final String[] arr3 = string.split("\\*", 2);
        int integer2 = 0;
        Label_0049: {
            if (arr3.length == 2) {
                try {
                    integer2 = Math.max(Integer.parseInt(arr3[0]), 0);
                    break Label_0049;
                }
                catch (NumberFormatException numberFormatException5) {
                    PresetFlatWorldScreen.LOGGER.error("Error while parsing flat world string => {}", numberFormatException5.getMessage());
                    return null;
                }
            }
            integer2 = 1;
        }
        final int integer3 = Math.min(integer + integer2, 256);
        final int integer4 = integer3 - integer;
        final String string2 = arr3[arr3.length - 1];
        Block bvr7;
        try {
            bvr7 = Registry.BLOCK.getOptional(new ResourceLocation(string2)).orElse(null);
        }
        catch (Exception exception9) {
            PresetFlatWorldScreen.LOGGER.error("Error while parsing flat world string => {}", exception9.getMessage());
            return null;
        }
        if (bvr7 == null) {
            PresetFlatWorldScreen.LOGGER.error("Error while parsing flat world string => Unknown block, {}", string2);
            return null;
        }
        final FlatLayerInfo cqz9 = new FlatLayerInfo(integer4, bvr7);
        cqz9.setStart(integer);
        return cqz9;
    }
    
    private static List<FlatLayerInfo> getLayersInfoFromString(final String string) {
        final List<FlatLayerInfo> list2 = Lists.newArrayList();
        final String[] arr3 = string.split(",");
        int integer4 = 0;
        for (final String string2 : arr3) {
            final FlatLayerInfo cqz9 = getLayerInfoFromString(string2, integer4);
            if (cqz9 == null) {
                return Collections.<FlatLayerInfo>emptyList();
            }
            list2.add(cqz9);
            integer4 += cqz9.getHeight();
        }
        return list2;
    }
    
    public static FlatLevelGeneratorSettings fromString(final String string, final FlatLevelGeneratorSettings cra) {
        final Iterator<String> iterator3 = Splitter.on(';').split(string).iterator();
        if (!iterator3.hasNext()) {
            return FlatLevelGeneratorSettings.getDefault();
        }
        final List<FlatLayerInfo> list4 = getLayersInfoFromString(iterator3.next());
        if (list4.isEmpty()) {
            return FlatLevelGeneratorSettings.getDefault();
        }
        final FlatLevelGeneratorSettings cra2 = cra.withLayers(list4, cra.structureSettings());
        Biome bre6 = Biomes.PLAINS;
        if (iterator3.hasNext()) {
            try {
                final ResourceLocation uh7 = new ResourceLocation(iterator3.next());
                final Object o;
                final Object obj;
                bre6 = Registry.BIOME.getOptional(uh7).<Throwable>orElseThrow(() -> {
                    new IllegalArgumentException("Invalid Biome: " + obj);
                    return o;
                });
            }
            catch (Exception exception7) {
                PresetFlatWorldScreen.LOGGER.error("Error while parsing flat world string => {}", exception7.getMessage());
            }
        }
        cra2.setBiome(bre6);
        return cra2;
    }
    
    private static String save(final FlatLevelGeneratorSettings cra) {
        final StringBuilder stringBuilder2 = new StringBuilder();
        for (int integer3 = 0; integer3 < cra.getLayersInfo().size(); ++integer3) {
            if (integer3 > 0) {
                stringBuilder2.append(",");
            }
            stringBuilder2.append(cra.getLayersInfo().get(integer3));
        }
        stringBuilder2.append(";");
        stringBuilder2.append(Registry.BIOME.getKey(cra.getBiome()));
        return stringBuilder2.toString();
    }
    
    @Override
    protected void init() {
        this.minecraft.keyboardHandler.setSendRepeatsToGui(true);
        this.shareText = new TranslatableComponent("createWorld.customize.presets.share");
        this.listText = new TranslatableComponent("createWorld.customize.presets.list");
        (this.export = new EditBox(this.font, 50, 40, this.width - 100, 20, this.shareText)).setMaxLength(1230);
        this.export.setValue(save(this.parent.settings()));
        this.settings = this.parent.settings();
        this.children.add(this.export);
        this.list = new PresetsList();
        this.children.add(this.list);
        final FlatLevelGeneratorSettings cra3;
        this.selectButton = this.<Button>addButton(new Button(this.width / 2 - 155, this.height - 28, 150, 20, new TranslatableComponent("createWorld.customize.presets.select"), dni -> {
            cra3 = fromString(this.export.getValue(), this.settings);
            this.parent.setConfig(cra3);
            this.minecraft.setScreen(this.parent);
            return;
        }));
        this.<Button>addButton(new Button(this.width / 2 + 5, this.height - 28, 150, 20, CommonComponents.GUI_CANCEL, dni -> this.minecraft.setScreen(this.parent)));
        this.updateButtonValidity(this.list.getSelected() != null);
    }
    
    @Override
    public boolean mouseScrolled(final double double1, final double double2, final double double3) {
        return this.list.mouseScrolled(double1, double2, double3);
    }
    
    @Override
    public void resize(final Minecraft dlx, final int integer2, final int integer3) {
        final String string5 = this.export.getValue();
        this.init(dlx, integer2, integer3);
        this.export.setValue(string5);
    }
    
    @Override
    public void onClose() {
        this.minecraft.setScreen(this.parent);
    }
    
    @Override
    public void removed() {
        this.minecraft.keyboardHandler.setSendRepeatsToGui(false);
    }
    
    @Override
    public void render(final PoseStack dhl, final int integer2, final int integer3, final float float4) {
        this.renderBackground(dhl);
        this.list.render(dhl, integer2, integer3, float4);
        RenderSystem.pushMatrix();
        RenderSystem.translatef(0.0f, 0.0f, 400.0f);
        this.drawCenteredString(dhl, this.font, this.title, this.width / 2, 8, 16777215);
        this.drawString(dhl, this.font, this.shareText, 50, 30, 10526880);
        this.drawString(dhl, this.font, this.listText, 50, 70, 10526880);
        RenderSystem.popMatrix();
        this.export.render(dhl, integer2, integer3, float4);
        super.render(dhl, integer2, integer3, float4);
    }
    
    @Override
    public void tick() {
        this.export.tick();
        super.tick();
    }
    
    public void updateButtonValidity(final boolean boolean1) {
        this.selectButton.active = (boolean1 || this.export.getValue().length() > 1);
    }
    
    private static void preset(final Component mr, final ItemLike bqa, final Biome bre, final List<StructureFeature<?>> list, final boolean boolean5, final boolean boolean6, final boolean boolean7, final FlatLayerInfo... arr) {
        final Map<StructureFeature<?>, StructureFeatureConfiguration> map9 = Maps.newHashMap();
        for (final StructureFeature<?> cml11 : list) {
            map9.put(cml11, StructureSettings.DEFAULTS.get(cml11));
        }
        final StructureSettings ciw10 = new StructureSettings(boolean5 ? Optional.<StrongholdConfiguration>of(StructureSettings.DEFAULT_STRONGHOLD) : Optional.<StrongholdConfiguration>empty(), map9);
        final FlatLevelGeneratorSettings cra11 = new FlatLevelGeneratorSettings(ciw10);
        if (boolean6) {
            cra11.setDecoration();
        }
        if (boolean7) {
            cra11.setAddLakes();
        }
        for (int integer12 = arr.length - 1; integer12 >= 0; --integer12) {
            cra11.getLayersInfo().add(arr[integer12]);
        }
        cra11.setBiome(bre);
        cra11.updateLayers();
        PresetFlatWorldScreen.PRESETS.add(new PresetInfo(bqa.asItem(), mr, cra11.withStructureSettings(ciw10)));
    }
    
    static {
        LOGGER = LogManager.getLogger();
        PRESETS = Lists.newArrayList();
        preset(new TranslatableComponent("createWorld.customize.preset.classic_flat"), Blocks.GRASS_BLOCK, Biomes.PLAINS, Arrays.<StructureFeature<?>>asList(StructureFeature.VILLAGE), false, false, false, new FlatLayerInfo(1, Blocks.GRASS_BLOCK), new FlatLayerInfo(2, Blocks.DIRT), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.tunnelers_dream"), Blocks.STONE, Biomes.MOUNTAINS, Arrays.<StructureFeature<?>>asList(StructureFeature.MINESHAFT), true, true, false, new FlatLayerInfo(1, Blocks.GRASS_BLOCK), new FlatLayerInfo(5, Blocks.DIRT), new FlatLayerInfo(230, Blocks.STONE), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.water_world"), Items.WATER_BUCKET, Biomes.DEEP_OCEAN, Arrays.<StructureFeature<?>>asList(StructureFeature.OCEAN_RUIN, StructureFeature.SHIPWRECK, StructureFeature.OCEAN_MONUMENT), false, false, false, new FlatLayerInfo(90, Blocks.WATER), new FlatLayerInfo(5, Blocks.SAND), new FlatLayerInfo(5, Blocks.DIRT), new FlatLayerInfo(5, Blocks.STONE), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.overworld"), Blocks.GRASS, Biomes.PLAINS, Arrays.<StructureFeature<?>>asList(StructureFeature.VILLAGE, StructureFeature.MINESHAFT, StructureFeature.PILLAGER_OUTPOST, StructureFeature.RUINED_PORTAL), true, true, true, new FlatLayerInfo(1, Blocks.GRASS_BLOCK), new FlatLayerInfo(3, Blocks.DIRT), new FlatLayerInfo(59, Blocks.STONE), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.snowy_kingdom"), Blocks.SNOW, Biomes.SNOWY_TUNDRA, Arrays.<StructureFeature<?>>asList(StructureFeature.VILLAGE, StructureFeature.IGLOO), false, false, false, new FlatLayerInfo(1, Blocks.SNOW), new FlatLayerInfo(1, Blocks.GRASS_BLOCK), new FlatLayerInfo(3, Blocks.DIRT), new FlatLayerInfo(59, Blocks.STONE), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.bottomless_pit"), Items.FEATHER, Biomes.PLAINS, Arrays.<StructureFeature<?>>asList(StructureFeature.VILLAGE), false, false, false, new FlatLayerInfo(1, Blocks.GRASS_BLOCK), new FlatLayerInfo(3, Blocks.DIRT), new FlatLayerInfo(2, Blocks.COBBLESTONE));
        preset(new TranslatableComponent("createWorld.customize.preset.desert"), Blocks.SAND, Biomes.DESERT, Arrays.<StructureFeature<?>>asList(StructureFeature.VILLAGE, StructureFeature.DESERT_PYRAMID, StructureFeature.MINESHAFT), true, true, false, new FlatLayerInfo(8, Blocks.SAND), new FlatLayerInfo(52, Blocks.SANDSTONE), new FlatLayerInfo(3, Blocks.STONE), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.redstone_ready"), Items.REDSTONE, Biomes.DESERT, Collections.<StructureFeature<?>>emptyList(), false, false, false, new FlatLayerInfo(52, Blocks.SANDSTONE), new FlatLayerInfo(3, Blocks.STONE), new FlatLayerInfo(1, Blocks.BEDROCK));
        preset(new TranslatableComponent("createWorld.customize.preset.the_void"), Blocks.BARRIER, Biomes.THE_VOID, Collections.<StructureFeature<?>>emptyList(), false, true, false, new FlatLayerInfo(1, Blocks.AIR));
    }
    
    class PresetsList extends ObjectSelectionList<Entry> {
        public PresetsList() {
            super(PresetFlatWorldScreen.this.minecraft, PresetFlatWorldScreen.this.width, PresetFlatWorldScreen.this.height, 80, PresetFlatWorldScreen.this.height - 37, 24);
            for (int integer3 = 0; integer3 < PresetFlatWorldScreen.PRESETS.size(); ++integer3) {
                this.addEntry(new Entry());
            }
        }
        
        @Override
        public void setSelected(@Nullable final Entry a) {
            super.setSelected(a);
            if (a != null) {
                NarratorChatListener.INSTANCE.sayNow(new TranslatableComponent("narrator.select", new Object[] { PresetFlatWorldScreen.PRESETS.get(this.children().indexOf(a)).getName() }).getString());
            }
            PresetFlatWorldScreen.this.updateButtonValidity(a != null);
        }
        
        @Override
        protected boolean isFocused() {
            return PresetFlatWorldScreen.this.getFocused() == this;
        }
        
        @Override
        public boolean keyPressed(final int integer1, final int integer2, final int integer3) {
            if (super.keyPressed(integer1, integer2, integer3)) {
                return true;
            }
            if ((integer1 == 257 || integer1 == 335) && this.getSelected() != null) {
                this.getSelected().select();
            }
            return false;
        }
        
        public class Entry extends ObjectSelectionList.Entry<Entry> {
            @Override
            public void render(final PoseStack dhl, final int integer2, final int integer3, final int integer4, final int integer5, final int integer6, final int integer7, final int integer8, final boolean boolean9, final float float10) {
                final PresetInfo a12 = PresetFlatWorldScreen.PRESETS.get(integer2);
                this.blitSlot(dhl, integer4, integer3, a12.icon);
                PresetFlatWorldScreen.this.font.draw(dhl, a12.name, (float)(integer4 + 18 + 5), (float)(integer3 + 6), 16777215);
            }
            
            @Override
            public boolean mouseClicked(final double double1, final double double2, final int integer) {
                if (integer == 0) {
                    this.select();
                }
                return false;
            }
            
            private void select() {
                PresetsList.this.setSelected(this);
                final PresetInfo a2 = PresetFlatWorldScreen.PRESETS.get(PresetsList.this.children().indexOf(this));
                PresetFlatWorldScreen.this.export.setValue(save(a2.settings));
                PresetFlatWorldScreen.this.export.moveCursorToStart();
                PresetFlatWorldScreen.this.settings = a2.settings;
            }
            
            private void blitSlot(final PoseStack dhl, final int integer2, final int integer3, final Item bke) {
                this.blitSlotBg(dhl, integer2 + 1, integer3 + 1);
                RenderSystem.enableRescaleNormal();
                PresetFlatWorldScreen.this.itemRenderer.renderGuiItem(new ItemStack(bke), integer2 + 2, integer3 + 2);
                RenderSystem.disableRescaleNormal();
            }
            
            private void blitSlotBg(final PoseStack dhl, final int integer2, final int integer3) {
                RenderSystem.color4f(1.0f, 1.0f, 1.0f, 1.0f);
                PresetsList.this.minecraft.getTextureManager().bind(GuiComponent.STATS_ICON_LOCATION);
                GuiComponent.blit(dhl, integer2, integer3, PresetFlatWorldScreen.this.getBlitOffset(), 0.0f, 0.0f, 18, 18, 128, 128);
            }
        }
    }
    
    static class PresetInfo {
        public final Item icon;
        public final Component name;
        public final FlatLevelGeneratorSettings settings;
        
        public PresetInfo(final Item bke, final Component mr, final FlatLevelGeneratorSettings cra) {
            this.icon = bke;
            this.name = mr;
            this.settings = cra;
        }
        
        public Component getName() {
            return this.name;
        }
    }
}
