/* 2010-03-15
 */
package com.cwasa.javacv;


import java.io.IOException;

import java.net.Socket;
import java.net.ServerSocket;


import com.cwasa.javacv.Logging;

import static com.cwasa.javacv.JAVideoServiceThread.VIDEO_SERVICE_CHECK_PORT;


public class JAVideoServiceCheckThread extends Thread {

	public static final String				VSCT_TAG = "JA Video Service Check Thread";

	private final Logging					LOG;

/** Writes the given message to the log. */
	//private void log(String msg)	{ System.out.println(msg); }
	private void log(String msg)	{ this.LOG.log(msg); }
/** Writes the standard prefix tag and then the given message to the log. */
	private void logt(String msg)	{ this.log(VSCT_TAG+msg); }

	private final ServerSocket				CHECK_SOCKET;

	public JAVideoServiceCheckThread(Logging log) throws IOException {

		this.LOG = log;
		this.CHECK_SOCKET = new ServerSocket(VIDEO_SERVICE_CHECK_PORT, 1);
	}

	public void shutDown() throws IOException { this.CHECK_SOCKET.close(); }

	public void run() {

		this.logt(" starts.");

		try {
			while (true) {
				Socket ccsckt = this.CHECK_SOCKET.accept();
				this.logt(": check received.");
				if (!this.isValid(ccsckt)) { Thread.sleep(500); }
			}
		}
		catch (IOException iox) { this.logt(": "+ iox); }
		catch (InterruptedException ix) {
			this.logt(": "+ ix);
			Thread.currentThread().interrupt();
		}

		this.logt(" done.");
	}

	private boolean isValid(Socket ccsckt) {

		boolean ok = false;
		try {
			JAVideoServiceThread.checkLocal(ccsckt);
			ok = true;
		}
		catch (IOException iox) { this.logt(" check validation fails: "+iox); }

		return ok;
	}
}
