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

import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

//import net.bakingpowder.tmiz.proxy.Input2Output;
//import net.bakingpowder.tmiz.proxy.MyProxy;

/**
 * @author Tomoo D. Mizukami/JAIST/Softbank Publishing Inc.
 * 
 * This Class is a multi thread class for controling trafic between
 * InputStream/OutputStream and buffer-interchange-function
 */
public class SendConnectControl implements Runnable {
	private boolean connectionClosed = false;
	private InputStream destIn, srcIn;
	private OutputStream srcOut, destOut;

	private SendInput2Output src2dst, dst2src;
	private Socket srcSocket, destSocket;

	private String destHost;
	private int destPort;
	

	public SendConnectControl(Socket ss, Socket ds,String destHost,int destPortNumber) {
		srcSocket = ss;
		destSocket = ds;
		this.destHost = destHost;
		this.destPort = destPortNumber;

		try {
			srcIn = ss.getInputStream();
			srcOut = ss.getOutputStream();
			destIn = ds.getInputStream();
			destOut = ds.getOutputStream();

			destOut.write(destHost.getBytes().length);
			destOut.write(destHost.getBytes());
			destOut.write(new Integer(destPortNumber).toString().getBytes().length);
			destOut.write(new Integer(destPortNumber).toString().getBytes());
			
			Thread t = new Thread(this);
			t.start();
		} catch (IOException e) {
			System.err.println("[Proxy Connection Error]");
			e.printStackTrace();
		}
	}
	
	public synchronized void ThreadArrivedEnd(SendInput2Output a) {
		if (connectionClosed)
			return;

		this.closeSrc();
		this.closeDest();

		connectionClosed = true;
	}

	private void closeDest() {
		try {
			destIn.close();
			destOut.close();
			destSocket.close();
		} catch (Exception e) {
		}
	}

	private void closeSrc() {
		try {
			srcIn.close();
			srcOut.close();
			srcSocket.close();
		} catch (Exception e) {
		}
	}

	public void stopd() {
		if (src2dst == null) {
			src2dst.stopd();
		}
		if (dst2src == null) {
			dst2src.stopd();
		}
	}

	public void run() {
				src2dst = new SendInput2Output(srcIn, destOut, this);
				dst2src = new SendInput2Output(destIn, srcOut, this);
	}
}