package fr.bglands.client.fabric;

import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.loader.api.FabricLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class BgLandsClient implements ClientModInitializer {
    public static final String MOD_ID = "bglands_client";
    public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);

    private static final BgLandsConnection CONNECTION = new BgLandsConnection(resolveVersion());

    @Override
    public void onInitializeClient() {
        PayloadTypeRegistry.clientboundPlay().register(BgLandsRawPayload.TYPE, BgLandsRawPayload.CODEC);
        PayloadTypeRegistry.serverboundPlay().register(BgLandsRawPayload.TYPE, BgLandsRawPayload.CODEC);

        ClientPlayNetworking.registerGlobalReceiver(BgLandsRawPayload.TYPE, (payload, context) ->
                CONNECTION.receive(context.client(), payload.data())
        );
        ClientPlayConnectionEvents.JOIN.register((listener, sender, client) -> CONNECTION.join(sender));
        ClientPlayConnectionEvents.DISCONNECT.register((listener, client) -> CONNECTION.disconnect(client));
        BgLandsLauncherHud.register();

        LOGGER.info("BG Lands client {} initialized (protocol 1.0)", resolveVersion());
    }

    private static String resolveVersion() {
        return FabricLoader.getInstance()
                .getModContainer(MOD_ID)
                .map(container -> container.getMetadata().getVersion().getFriendlyString())
                .orElse("development");
    }
}
