package org.holer.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.net.InetSocketAddress;
import org.holer.server.util.DataCollector;


public class DataHandler extends ChannelDuplexHandler {

  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    InetSocketAddress addr = (InetSocketAddress)ctx.channel().localAddress();
    DataCollector collector = DataCollector.getCollector(addr.getPort());
    collector.incrementReadBytes(((ByteBuf)msg).readableBytes());
    collector.incrementReadMsgs(1L);
    ctx.fireChannelRead(msg);
  }


  
  public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    InetSocketAddress addr = (InetSocketAddress)ctx.channel().localAddress();
    DataCollector collector = DataCollector.getCollector(addr.getPort());
    collector.incrementWroteBytes(((ByteBuf)msg).readableBytes());
    collector.incrementWroteMsgs(1L);
    super.write(ctx, msg, promise);
  }


  
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress addr = (InetSocketAddress)ctx.channel().localAddress();
    DataCollector collector = DataCollector.getCollector(addr.getPort());
    collector.getChannels().incrementAndGet();
    super.channelActive(ctx);
  }


  
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress addr = (InetSocketAddress)ctx.channel().localAddress();
    DataCollector collector = DataCollector.getCollector(addr.getPort());
    collector.getChannels().decrementAndGet();
    super.channelInactive(ctx);
  }
}
