package net.minecraft.client.gui.screens;

import org.apache.logging.log4j.LogManager;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.Util;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.DefaultUncaughtExceptionHandler;
import java.net.UnknownHostException;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.PacketListener;
import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl;
import java.net.InetAddress;
import net.minecraft.client.multiplayer.ServerAddress;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.network.Connection;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.atomic.AtomicInteger;

public class ConnectScreen extends Screen {
    private static final AtomicInteger UNIQUE_THREAD_ID;
    private static final Logger LOGGER;
    private Connection connection;
    private boolean aborted;
    private final Screen parent;
    private Component status;
    private long lastNarration;
    
    public ConnectScreen(final Screen dqs, final Minecraft dlx, final ServerData dys) {
        super(NarratorChatListener.NO_TITLE);
        this.status = new TranslatableComponent("connect.connecting");
        this.lastNarration = -1L;
        this.minecraft = dlx;
        this.parent = dqs;
        final ServerAddress dyr5 = ServerAddress.parseString(dys.ip);
        dlx.clearLevel();
        dlx.setCurrentServer(dys);
        this.connect(dyr5.getHost(), dyr5.getPort());
    }
    
    public ConnectScreen(final Screen dqs, final Minecraft dlx, final String string, final int integer) {
        super(NarratorChatListener.NO_TITLE);
        this.status = new TranslatableComponent("connect.connecting");
        this.lastNarration = -1L;
        this.minecraft = dlx;
        this.parent = dqs;
        dlx.clearLevel();
        this.connect(string, integer);
    }
    
    private void connect(final String string, final int integer) {
        ConnectScreen.LOGGER.info("Connecting to {}, {}", string, integer);
        final Thread thread4 = new Thread("Server Connector #" + ConnectScreen.UNIQUE_THREAD_ID.incrementAndGet()) {
            @Override
            public void run() {
                InetAddress inetAddress2 = null;
                try {
                    if (ConnectScreen.this.aborted) {
                        return;
                    }
                    inetAddress2 = InetAddress.getByName(string);
                    ConnectScreen.this.connection = Connection.connectToServer(inetAddress2, integer, ConnectScreen.this.minecraft.options.useNativeTransport());
                    ConnectScreen.this.connection.setListener(new ClientHandshakePacketListenerImpl(ConnectScreen.this.connection, ConnectScreen.this.minecraft, ConnectScreen.this.parent, mr -> ConnectScreen.this.updateStatus(mr)));
                    ConnectScreen.this.connection.send(new ClientIntentionPacket(string, integer, ConnectionProtocol.LOGIN));
                    ConnectScreen.this.connection.send(new ServerboundHelloPacket(ConnectScreen.this.minecraft.getUser().getGameProfile()));
                }
                catch (UnknownHostException unknownHostException3) {
                    if (ConnectScreen.this.aborted) {
                        return;
                    }
                    ConnectScreen.LOGGER.error("Couldn't connect to server", (Throwable)unknownHostException3);
                    final Minecraft minecraft;
                    final TranslatableComponent mr2;
                    final Screen screen;
                    final Screen dqs;
                    final String string5;
                    ConnectScreen.this.minecraft.execute(() -> {
                        minecraft = ConnectScreen.this.minecraft;
                        // new(net.minecraft.client.gui.screens.DisconnectedScreen.class)
                        ConnectScreen.this.parent;
                        new TranslatableComponent("disconnect.genericReason", new Object[] { "Unknown host" });
                        new DisconnectedScreen(dqs, string5, mr2);
                        minecraft.setScreen(screen);
                    });
                }
                catch (Exception exception3) {
                    if (ConnectScreen.this.aborted) {
                        return;
                    }
                    ConnectScreen.LOGGER.error("Couldn't connect to server", (Throwable)exception3);
                    final String string4 = (inetAddress2 == null) ? exception3.toString() : exception3.toString().replaceAll(inetAddress2 + ":" + integer, "");
                    final Minecraft minecraft2;
                    final Component mr3;
                    final Object o;
                    final Screen screen2;
                    final Screen dqs2;
                    final String string6;
                    ConnectScreen.this.minecraft.execute(() -> {
                        minecraft2 = ConnectScreen.this.minecraft;
                        // new(net.minecraft.client.gui.screens.DisconnectedScreen.class)
                        ConnectScreen.this.parent;
                        new TranslatableComponent("disconnect.genericReason", new Object[] { o });
                        new DisconnectedScreen(dqs2, string6, mr3);
                        minecraft2.setScreen(screen2);
                    });
                }
            }
        };
        thread4.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(ConnectScreen.LOGGER));
        thread4.start();
    }
    
    private void updateStatus(final Component mr) {
        this.status = mr;
    }
    
    @Override
    public void tick() {
        if (this.connection != null) {
            if (this.connection.isConnected()) {
                this.connection.tick();
            }
            else {
                this.connection.handleDisconnection();
            }
        }
    }
    
    @Override
    public boolean shouldCloseOnEsc() {
        return false;
    }
    
    @Override
    protected void init() {
        this.<Button>addButton(new Button(this.width / 2 - 100, this.height / 4 + 120 + 12, 200, 20, CommonComponents.GUI_CANCEL, dni -> {
            this.aborted = true;
            if (this.connection != null) {
                this.connection.disconnect(new TranslatableComponent("connect.aborted"));
            }
            this.minecraft.setScreen(this.parent);
        }));
    }
    
    @Override
    public void render(final PoseStack dhl, final int integer2, final int integer3, final float float4) {
        this.renderBackground(dhl);
        final long long6 = Util.getMillis();
        if (long6 - this.lastNarration > 2000L) {
            this.lastNarration = long6;
            NarratorChatListener.INSTANCE.sayNow(new TranslatableComponent("narrator.joining").getString());
        }
        this.drawCenteredString(dhl, this.font, this.status, this.width / 2, this.height / 2 - 50, 16777215);
        super.render(dhl, integer2, integer3, float4);
    }
    
    static {
        UNIQUE_THREAD_ID = new AtomicInteger(0);
        LOGGER = LogManager.getLogger();
    }
}
