package net.cobem.grizzly.net;

import net.cobem.grizzly.Grizzly;
import net.cobem.grizzly.communication.EventRequest;
import net.cobem.grizzly.habbohotel.sessions.Session;
import org.jboss.netty.channel.*;



/*
 * From Crowley
 * Thanks Jordan
 */

public class ConnectionHandler extends SimpleChannelUpstreamHandler {
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        //if (e instanceof ChannelStateEvent)
        {
            Grizzly.getHabboHotel().getSessions().create(ctx.getChannel());
        }
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
        //if (e instanceof ChannelStateEvent)
        {
            Session mSession = (Session) ctx.getChannel().getAttachment();

            Grizzly.getHabboHotel().getSessions().kill(mSession);
        }
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
        //if (e instanceof ChannelStateEvent)
        {
            Session mSession = (Session) ctx.getChannel().getAttachment();

            Grizzly.getHabboHotel().getSessions().kill(mSession);
        }
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        try {
            Grizzly.getConnections().getEventHandler().handleRequest(
                    Grizzly.getHabboHotel().getSessions().get(ctx.getChannel()), (EventRequest) e.getMessage());
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        e.getChannel().close();
    }
}
