package daruma.server;

import daruma.server.DarumaDaemon;
import daruma.util.LogWriter;
import daruma.util.Itk;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.SocketException;
import java.io.IOException;


public class DarumaDaemonAdministrator implements Runnable
{
    private final DarumaDaemon daemon;
    private final int adminPort;

    DarumaDaemonAdministrator( DarumaDaemon daemon, int adminPort )
    {
	this.daemon = daemon;
	this.adminPort = adminPort;
    }

    public void run()
    {
	ServerSocket adminSocket;

	try
	{
	    adminSocket = new ServerSocket( this.adminPort );

	    LogWriter.qwrite( "INFO",
			      "[" + Itk.getCurrentTimeStr() + "] ",
			      "Admin Port Listen:", adminSocket );

	    while( true )
	    {
		Socket s = adminSocket.accept();

		LogWriter.qwrite( "INFO",
				  "[" + Itk.getCurrentTimeStr() + "] ",
				  "Admin Port Open :", s );

		final String command = "forceDisconectClient";

		try
		{
		    if ( command.equals( "forceDisconectClient" ) )
		    {
			this.forceDisconectClient();
		    }
		}
		catch( IOException e )
		{
		    e.printStackTrace();
		}

		try
		{
		    LogWriter.qwrite( "INFO",
				      "[" + Itk.getCurrentTimeStr() + "] ",
				      "Admin Port Close :", s );
		    s.close();
		}
		catch( SocketException e )
		{
		    e.printStackTrace();
		}
	    }
	}
	catch( IOException e )
	{
	    e.printStackTrace();
	}
    }

    public void forceDisconectClient() throws IOException
    {
	synchronized( daemon.adminLock )
	{
	    if ( daemon.admin.currentClientSocket != null )
	    {
		LogWriter.qwrite( "INFO",
				  "closing client Socket: ",
				  daemon.admin.currentClientSocket );

		daemon.admin.currentClientSocket.close();
	    }
	}
    }
}
