package net.bakingpowder.jspl.tcprelay.buffering;

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

/**
 *
 * This Library provide you a simple and light-weight proxy solution.
 *
 * <pre>
 * If you'd like to use,Then
 * 
 * You can use like this:
 * 
 * <h4>At Starting</h4>
 * TCPRelay tr = new TCPRelay(port1,Address,port2);
 * Thread t = new Thread(tr);
 * t.start();
 * 
 * <h4>At Stoping</h4>
 * tr.setStopper(true);
 * </pre>
 * @author Tomoo D. Mizukami/JAIST/Softbank Publishing Inc.
 *
 */
public class TCPRelay implements Runnable {
	private String destHost = null;
	private ServerSocket mainSocket = null;
	private int portNumber, destPortNumber;
	private boolean stopper = false;
	
	/**
	 * @param portNumber
	 *            Listening Local PortNumber
	 * @param destHost
	 *            Destination Host Address
	 * @param destPortNumber
	 *            Destination Host PortNumber
	 * @throws Exception
	 */
	public TCPRelay(int portNumber, String destHost, int destPortNumber)
			throws Exception {
		this.portNumber = portNumber;
		this.destHost = destHost;
		this.destPortNumber = destPortNumber;

		mainSocket = new ServerSocket(portNumber);
	}

	/**
	 * Let Proxy Service start.
	 */
	public void service_start() {
		while (true) {
			try {
				Socket newSocket = mainSocket.accept();
				new ConnectControl(newSocket, destHost, destPortNumber);

			} catch (IOException e) {
				//ignore
			}
		}
	}
	
	/**
	 * @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 ConnectControl cc;
	
	public void run() {
		while (!stopper) {
			try {
				Socket newSocket = mainSocket.accept();
				cc = new ConnectControl(newSocket, destHost, destPortNumber);

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