package com.zivilon.cindercore_modlist.mixins;

import java.lang.reflect.Field;
import io.netty.channel.ChannelHandlerContext;
import cpw.mods.fml.common.network.handshake.FMLHandshakeMessage;
import cpw.mods.fml.common.network.handshake.FMLHandshakeServerState;
import cpw.mods.fml.common.network.handshake.NetworkDispatcher;
import cpw.mods.fml.common.network.handshake.FMLHandshakeMessage.ModList;
import net.minecraft.entity.player.EntityPlayerMP;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.relauncher.Side;
import java.util.Map;
import java.util.UUID;

import com.zivilon.cindercore_modlist.CinderCoreModlist;

@Mixin(targets = "cpw.mods.fml.common.network.handshake.FMLHandshakeServerState$2")
public abstract class MixinFMLHandshakeServerStateHELLO {

    @Inject(method = "accept", at = @At("RETURN"), cancellable = false)
    private void onAccept(ChannelHandlerContext ctx, FMLHandshakeMessage msg, CallbackInfoReturnable<FMLHandshakeServerState> cir) {
        if (msg == null || !(msg instanceof FMLHandshakeMessage.ModList)) {
            return;
        }
        System.out.println("[CinderCore] Initiating modified handshake HELLO");
        FMLHandshakeMessage.ModList modListMsg = (FMLHandshakeMessage.ModList) msg;
        Map<String, String> modList = modListMsg.modList();

        NetworkDispatcher dispatcher = ctx.channel().attr(NetworkDispatcher.FML_DISPATCHER).get();
        if (dispatcher == null) {
            return;
        }

        try {
            Field playerField = NetworkDispatcher.class.getDeclaredField("player");
            playerField.setAccessible(true);
            EntityPlayerMP player = (EntityPlayerMP) playerField.get(dispatcher);
            System.out.println("[CinderCore] Player " + player.getCommandSenderName() + " is connecting with mods " + modList);
            if (player != null) {
                CinderCoreModlist.savePlayerModList(player.getUniqueID(), modList);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
