package com.thebrokenrail.twine.packet;

import com.thebrokenrail.twine.Twine;
import io.netty.buffer.Unpooled;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.network.PacketContext;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ConfirmChatLinkScreen;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.Util;

public class OpenURLS2CPacket {
    @Environment(EnvType.CLIENT)
    public static void handle(PacketContext context, PacketByteBuf buf) {
        String url = buf.readString();
        MinecraftClient.getInstance().openScreen(new ConfirmChatLinkScreen(open -> {
            if (open) {
                Util.getOperatingSystem().open(url);
            }
            MinecraftClient.getInstance().openScreen(null);
        }, url, false));
    }

    public static void send(ServerPlayerEntity player, String url) {
        PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
        buf.writeString(url);
        player.networkHandler.sendPacket(new CustomPayloadS2CPacket(new Identifier(Twine.NAMESPACE, "open_url"), buf));
    }
}
