package org.kne.cloud.network.klalb;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.NoRouteToHostException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

public class SendTask {
	private int maxcount;
	private AtomicInteger count=new AtomicInteger();
	private int priority;
	private Inet6Address address;
	private volatile long starttime=System.nanoTime(); 
	private void resetTime() {
		starttime=System.nanoTime(); 
	}
	private boolean checkTime(long limit) {
		long curr=System.nanoTime();
		boolean b=curr-starttime>limit;
		if(b)
			starttime=curr;
		return b;
	}
	public SendTask( KLALBController controllker,Inet6Address address,DATATPacket kp,int priority,int maxcount) {
		super();
		this.maxcount = maxcount;
		this.controllker = controllker;
		this.packet = kp;
		this.address=address;
		this.priority=priority;
	}





	public KLALBController getControllker() {
		return controllker;
	}


	public DATATPacket getPacket() {
		return packet;
	}


	private KLALBController controllker;
	private DATATPacket packet;
	

	public int getMaxcount() {
		return maxcount;
	}



	
	public void check(int number) throws IOException {
		long limit= count.get()*(1000*number+500)*1000000L;
		if(checkTime(limit))
			run();
	}
	
	
	public void run() throws IOException {
		if(count.get()>=maxcount) {
			throw new IOException("send error!");
		}
		try {
			if(count.get()==0) {
			controllker.sendPacketToAddress((Inet6Address) address,
					packet, priority,1);
			}else {
				controllker.sendPacketToAddress((Inet6Address) address,
						packet, priority-1,1);
			}
		} catch (NoRouteToHostException e) {
		}
		resetTime();
		count.incrementAndGet();
		if(count.get()>1) {
			System.out.println("第"+(count.get()-1)+"次重传："+packet);
		}
		
	}
	
}
