package jnet.server.network;

import jnet.server.ServerMessageParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import jnet.lib.LogFile;
import jnet.lib.Message;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof Message) {
            Message m = (Message) msg;
            new ServerMessageParser(ctx.channel()).parse((Message) msg);
        }
        if (msg instanceof String) {
            System.out.println("Client message: " + msg);
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client connected");
        Channel currentClient = ctx.channel();
        currentClient.writeAndFlush(new Message(Message.CLIENT_VERSION, null));
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        LogFile.printInfo("Client disconnected");
        ServerMessageParser.removeClient(ctx.channel());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}