package org.kne.cloud.network.klalb;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.atomic.AtomicLong;

public class MonitoredChannel implements Channel,ReadableByteChannel ,WritableByteChannel{
	
	private Channel channel;
	private AtomicLong[] totalIn;
	private AtomicLong[] totalOut;

	public MonitoredChannel (Channel channel,AtomicLong[] totalIn,AtomicLong[] totalOut) {
		this.channel=channel;
		this.totalIn=totalIn;
		this.totalOut=totalOut;
	}
	
	public Channel getChannel() {
		return channel;
	}

	@Override
	public boolean isOpen() {
		return channel.isOpen();
	}

	@Override
	public void close() throws IOException {
		channel.close();
	}

	@Override
	public int write(ByteBuffer src) throws IOException {
		int count=((WritableByteChannel)channel).write(src);
		for(AtomicLong x:totalOut)
			x.addAndGet(count);
		return count;
	}

	@Override
	public int read(ByteBuffer dst) throws IOException {
		int count=((ReadableByteChannel)channel).read(dst);
		if(count!=-1) {
			for(AtomicLong x:totalIn)
			x.incrementAndGet();
		}
		return count;
	}

}
