package com.tsi.app.common.xnet;

import io.netty.channel.Channel;

import java.net.InetSocketAddress;

public abstract class NettyStats {

    protected Channel channel;
    protected long recordReceived;
    protected long recordSent;
    protected long bytesReceived;
    protected long bytesSent;
    protected long minLatency;
    protected long maxLatency;
    protected long count;
    protected long totalLatency;

    public abstract InetSocketAddress getRemoteSocketAddress();

    public NettyStats() {
        reset();
    }

    public synchronized void setChannel(Channel chn) {
        channel = chn;
    }
    public synchronized Channel getChannel() {
        return channel;
    }

    public synchronized void reset() {
        recordReceived = 0;
        recordSent = 0;
        bytesReceived = 0;
        bytesSent = 0;
        minLatency = Long.MAX_VALUE;
        maxLatency = 0;
        count = 0;
        totalLatency = 0;
    }

    protected synchronized void updateStats(long start, long end, long receivedBytes, long sentBytes) {
        long elapsed = end - start;
        if (elapsed < minLatency) {
            minLatency = elapsed;
        }
        if (elapsed > maxLatency) {
            maxLatency = elapsed;
        }
        if (receivedBytes > 0) {
            recordReceived++;
            bytesReceived += receivedBytes;
        }
        if (sentBytes > 0) {
            recordSent++;
            bytesSent += sentBytes;
        }
        count++;
        totalLatency += elapsed;
    }

    public synchronized long getRecordReceived() {
        return recordReceived;
    }
    public synchronized long getRecordSent() {
        return recordSent;
    }

    public synchronized long getBytesReceived() {
        return bytesReceived;
    }
    public synchronized long getBytesSent() {
        return bytesSent;
    }

    public synchronized long getMinLatency(){
        return minLatency == Long.MAX_VALUE ? 0 : minLatency;
    }
    public synchronized long getMaxLatency(){
        return maxLatency;
    }
    public synchronized long getAvgLatency(){
        return count == 0 ? 0 : totalLatency / count;
    }
    public synchronized long getTotalLatency(){
        return totalLatency;
    }
    public synchronized long getCount(){
        return count;
    }
}
