package org.kne.cloud.network.perf;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.kne.cloud.network.MultiProtocolSocketAddress;
import org.kne.cloud.network.SocketChannelListener;
import org.kne.cloud.network.ThreadTool;
import org.kne.cloud.network.klalb.KLALBController;
import org.kne.cloud.network.klalb.KLALBRemoteLink;
import org.kne.cloud.network.klalb.StreamChannelKLALBPacketLink;

public class NodeBenchmark implements Runnable{
	private List<NodeEntry> nodeList=new ArrayList<>();
	private class NodeEntry{
		private SocketChannelListener scl;
		private KLALBController kc;
		public SocketChannelListener getScl() {
			return scl;
		}
		public KLALBController getKc() {
			return kc;
		}
		public NodeEntry(SocketChannelListener scl, KLALBController kc) {
			super();
			this.scl = scl;
			this.kc = kc;
		}
		
	}
	private KLALBController klalbController;
	private int nodes;
	public NodeBenchmark(KLALBController klalbController,int nodes) {
		this.klalbController=klalbController;
		this.nodes=nodes;
	}

	public void run() {
Random r=new Random();
for (int i = 0; i < nodes; i++) {
			KLALBController kct=new KLALBController(false);
			try {
				SocketChannelListener scl=new SocketChannelListener(ServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.8",0)));
				scl.setCon((c)->{
					try {
						kct.addRemoteLine(new KLALBRemoteLink(klalbController,new StreamChannelKLALBPacketLink(c)));
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
				System.out.println("KLALBController "+i+" created,locator:"+kct.getSelf());
				int size=nodeList.size();
				if(size>0) {
				for (int j = 0; j < 1; j++) {
					int ind=r.nextInt(size);
					NodeEntry ne=nodeList.get(ind);
					MultiProtocolSocketAddress mpsa=new MultiProtocolSocketAddress((InetSocketAddress) ne.getScl().getServerSocketChannel().getLocalAddress());
					kct.addRemoteLines(mpsa);
					System.out.println("connect:" +ne.getKc().getSelf().getAddress());
					
					
				}
				}
				nodeList.add(new NodeEntry( scl, kct));
			Thread.sleep(100);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
try {
NodeEntry ne=nodeList.get(0);
MultiProtocolSocketAddress mpsa=new MultiProtocolSocketAddress((InetSocketAddress) ne.getScl().getServerSocketChannel().getLocalAddress());
klalbController.addRemoteLines(mpsa);
} catch (IOException e) {
	e.printStackTrace();
}
	}

	public void startPerfing() {
		ThreadTool.makeVThreadIfSupport("节点数量测试线程" ,this).start();
	}

}
