package com.mingliqiye.minecraft.enchantment.conflict.network;

import com.google.gson.Gson;
import com.mingliqiye.minecraft.enchantment.conflict.config.ModConfig;
import com.mojang.logging.LogUtils;
import io.netty.buffer.Unpooled;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;

import com.mingliqiye.minecraft.enchantment.conflict.Mod;
import org.slf4j.Logger;

public class NetworkHandler {
    public static final Identifier CONFIG_PACKET_ID = new Identifier(Mod.MOD_ID, "config_packet");
    public static final Gson GSON = new Gson();

    private static final Logger LOGGER = LogUtils.getLogger();

    public static void sendConfigToClient(ServerPlayerEntity player) {
        PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
        buf.writeString(GSON.toJson(ModConfig.getInstance()));
        ServerPlayNetworking.send(player, NetworkHandler.CONFIG_PACKET_ID, buf);
        LOGGER.info("Send Player({}) Server {} config {}", player.getName().getString(), Mod.MOD_ID,
                ModConfig.getInstance());
    }

    public static void registerReceivers() {
        ClientPlayNetworking.registerGlobalReceiver(NetworkHandler.CONFIG_PACKET_ID,
                (client, handler, buf, responseSender) -> {
                    ModConfig configData = GSON.fromJson(buf.readString(), ModConfig.class);
                    client.execute(() -> {
                        ModConfig.setInstance(configData);
                        LOGGER.info("Load Server {} config {}", Mod.MOD_ID, configData);
                    });
                });
    }
}
