package net.bakingpowder.jspl.tcprelay.distributed.sendRelay;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;

/**
 * @author Tomoo D. Mizukami/JAIST/Softbank Publishing Inc.
 *
 * !)!)SendTCPRelay!)!)!)!)!)!)!)!)!)TCPRelay!)!)!)!)!)!)!)!)!)!)
 * !)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)
 */
public class SendTCPRelay implements Runnable {
	private String destHost = null;
	private String destRecieveTCPRelayAddress = null;

	private ServerSocket mainSocket = null;
	private int portNumber, destRecieveTCPRelayPort,destPortNumber;
	private boolean stopper = false;
	
	/**
	 * @param portNumber !)!)!)!)!)!)!)!)!)
	 * @param destRecieveTCPRelayAddress !)!)TCPRelay!)!)!)!)!)
	 * @param destRecieveTCPRelayPort !)!)TCPRelay!)!)!)!)!)!)
	 * @param destHost	!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)
	 * @param destPortNumber!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)
	 * @throws Exception !)!)!)!)
	 */
	public SendTCPRelay(int portNumber, String destRecieveTCPRelayAddress, int destRecieveTCPRelayPort,String destHost, int destPortNumber)
			throws Exception {
		this.portNumber = portNumber;
		this.destRecieveTCPRelayAddress = destRecieveTCPRelayAddress;
		this.destRecieveTCPRelayPort = destRecieveTCPRelayPort;

		this.destHost = destHost;
		this.destPortNumber = destPortNumber;
		
		mainSocket = new ServerSocket(portNumber);
	}
	
	/**
	 * @param stopper The stopper to set.
	 */
	public synchronized void setStopper(boolean stopper) {
		if (cc!=null){
			cc.stopd();
		}
		this.stopper = stopper;
		
		try {
			mainSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
	private SendConnectControl cc;
	
	public void run() {

		while (!stopper) {
			try {

				Socket newSocket = mainSocket.accept();
				Socket destSocket = new Socket(destRecieveTCPRelayAddress, destRecieveTCPRelayPort);

				System.out.println("SENDPROXY:Socket has been accepted!):"+ destPortNumber);
				
				cc = new SendConnectControl(newSocket,destSocket,destHost,destPortNumber);

			} catch (IOException e) {
				//ignore//
				System.out.println("IOException!!!");
			}
		}
		System.out.println("Proxy(" + portNumber + ":" + destHost + ":" + destPortNumber + ") is stopped.");	
		
		try {
			mainSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}