package org.kne.cloud.network.klalb;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.kne.cloud.network.VirtualServerSocket;
import org.kne.cloud.network.VirtualSocket;
import org.kne.cloud.network.VirtualSocketImpl;

public class KLALBVirtualServerSocket extends VirtualServerSocket {
	private KLALBController controler;
	protected ServerSocketChannel channel;
	public KLALBVirtualServerSocket(KLALBController controler) throws IOException {
		super(controler.createVirtualSocketImpl());
		this.controler=controler;
	}

	@Override
	protected KLALBVirtualSocketImpl getVirtualImpl() {
		return (KLALBVirtualSocketImpl) super.getVirtualImpl();
	}

	public KLALBVirtualServerSocket(KLALBController controler,int port) throws IOException {
        this(controler,port, 50, null);
    }

    
    public KLALBVirtualServerSocket(KLALBController controler,int port, int backlog) throws IOException {
        this(controler,port, backlog, null);
    }

    public KLALBVirtualServerSocket(KLALBController controler,int port, int backlog, InetAddress bindAddr) throws IOException {
    	this(controler);
        if (backlog < 1)
          backlog = 50;
        try {
            bind(new InetSocketAddress(bindAddr, port), backlog);
        } catch(SecurityException e) {
            close();
            throw e;
        } catch(IOException e) {
            close();
            throw e;
        }
    }

	protected KLALBController getControler() {
		return controler;
	}

	@Override
	public KLALBVirtualSocket accept() throws IOException {
		KLALBVirtualSocket s2=new KLALBVirtualSocket(controler);
		implAccept(s2);
		return s2;
	}

	@Override
	public ServerSocketChannel getChannel() {
		return channel;
	}

}
