package org.kne.cloud.network.monitor;

import java.util.UUID;

import org.kne.cloud.clock.HighAccuracyClock;
import org.kne.cloud.network.klalb.KLALBUtils;

public class SpeedAndTrafficAndDelayMonitorDataImpl extends SpeedAndTrafficMonitorDataImpl implements SpeedAndTrafficMonitorData,DelayMonitorData{

	private long timewindowmax=500000000L;

	private DelaySampler upSampler=new DelaySampler();
	private DelaySampler downSampler=new DelaySampler();
	
	long stime=System.nanoTime();
@Override
	public void update() {
		super.update();
		upSampler.update();
		downSampler.update();
		if(upSampler.getSnapshotPacketCount()>0&&upSampler.getSnapshotTotalDelay()>0) {
		getUploadBandwidth(). recordPacket(KLALBUtils.createGlobalUUID(),0, 0, upSampler.getAvgDelayNanos());
		}
		if(downSampler.getSnapshotPacketCount()>0&&downSampler.getSnapshotTotalDelay()>0) {
		getDownloadBandwidth(). recordPacket(KLALBUtils.createGlobalUUID(),0, 0, downSampler.getAvgDelayNanos());
		}
		
		long time=System.nanoTime();
		if(time-stime>timewindowmax) {
			stime=time;
		long idelay=getInDelay();
		if(inDelayMin==Long.MAX_VALUE||idelay<=inDelayMin) {
			inDelayMin=idelay;
		}else{
			inDelayMin=(inDelayMin*99+idelay)/100;
		}
		long odelay=getOutDelay();
		if(outDelayMin==Long.MAX_VALUE||odelay<=outDelayMin) {
			outDelayMin=odelay;
		}else{
			outDelayMin=(outDelayMin*99+odelay)/100;
		}
		}
	}


	
	@Override
	public String toString() {
		StringBuilder sb=new StringBuilder(super.toString());
		sb.append(KLALBUtils.convertUintNanoDefalut( getOutDelay()) ).append("s").append("\t").append(KLALBUtils.convertUintNanoDefalut( getInDelay()) ).append("s").append("\t").append(KLALBUtils.convertUintNanoDefalut( getOutJitter()) ).append("s\t").append(KLALBUtils.convertUintNanoDefalut( getInJitter()) ).append("s\t");
		return sb.toString();
	}

	public SpeedAndTrafficAndDelayMonitorDataImpl(HighAccuracyClock clock) {
		super(clock);
		// TODO 自动生成的构造函数存根
	}

	public SpeedAndTrafficAndDelayMonitorDataImpl(TimestampMonitor<UUID> uploadBandwidth,
			TimestampMonitor<UUID> downloadBandwidth) {
		super(uploadBandwidth, downloadBandwidth);
		// TODO 自动生成的构造函数存根
	}

	@Override
	public long getOutDelay() {
		return super.getUploadBandwidth().getRecentDelay();
	}

	

	public void recordUploadDelay(long delay) {
		upSampler.recordDelay(delay);
	}

	public void recordDownloadDelay(long delay) {
		downSampler.recordDelay(delay);
	}
	

	@Override
	public long getInDelay() {
		return super.getDownloadBandwidth().getRecentDelay();
	}

	private volatile long outDelayMin=Long.MAX_VALUE;
	private volatile long outJitter;
	private volatile long inDelayMin=Long.MAX_VALUE;
	private volatile long inJitter;

	@Override
	public long getOutJitter() {
		return outJitter;
	}

	@Override
	public long getInJitter() {
		return inJitter;
	}

	public long getOutDelayMin() {
		return outDelayMin;
	}

	public long getInDelayMin() {
		return inDelayMin;
	}

	
	
}
