//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010  huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE----------------------------
package org.huihoo.willow.core;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.MarshalledObject;
import java.rmi.Remote;
import java.rmi.server.UnicastRemoteObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.huihoo.willow.Globals;
import org.huihoo.willow.LifecycleException;
import org.huihoo.willow.desktop.RemoteDesktopServiceImpl;
import org.huihoo.workflow.desktop.WorkflowDesktop;

public class DesktopConnector extends StandardConnecor
{
	protected static Log log = LogFactory.getLog(DesktopConnector.class);
	protected static final String info = "DesktopConnector/1.0";

	/**
	 * Return descriptive information about this DesktopServiceConnector implementation.
	 */
	public String getInfo()
	{
		return (info);
	}

	/**
		 * The request scheme that will be set on all requests received
		 * through this namingProvider.
		 */
	private String scheme = WorkflowDesktop.REMOTE_DESKTOP_PROTOCOL;

	/** The ServiceContext interface server implementation */
	protected RemoteDesktopServiceImpl desktopServiceImpl;
	private MarshalledObject serverStub;

	/** The naming server socket through which the ServiceContextImpl stub is vended */
	private ServerSocket serverSocket;

	/**
	 * The background thread.
	 */
	private Thread thread = null;

	/**
	 * The background thread completion semaphore.
	 */
	private boolean threadDone = false;

	public DesktopConnector()
	{
		this.port = 2126;
	}
	
	// ------------------------------------------------------ Lifecycle Methods

	/**
	 * Begin processing requests via this NamingServer.
	 *
	 * @exception LifecycleException if a fatal startup error occurs
	 */
	public void start() throws LifecycleException
	{
		// Validate and update our current state
		if (started)
		{
			log.info(sm.getString("desktopConnector.alreadyStarted"));
			return;
		}

		try
		{
			desktopServiceImpl = new RemoteDesktopServiceImpl(this);
		}
		catch (Throwable e)
		{
			e.printStackTrace();
		}

		lifecycle.fireLifecycleEvent(START_EVENT, null);
		threadStart();

		super.start();
	}

	/**
	 * Terminate processing requests via this NamingServer.
	 *
	 * @exception LifecycleException if a fatal shutdown error occurs
	 */
	public void stop() throws LifecycleException
	{

		// Validate and update our current state
		if (!started)
		{
			log.error(sm.getString("desktopConnector.notStarted"));
			return;

		}
		lifecycle.fireLifecycleEvent(STOP_EVENT, null);

		// Stop the existing server
		threadStop();
		super.stop();
	}

	/**
	 * Start the background thread that will periodically check for
	 * session timeouts.
	 */
	protected void threadStart()
	{

		if (thread != null)
			return;

		try
		{
			Remote namingStub = UnicastRemoteObject.exportObject(desktopServiceImpl, Globals.DESKTOP_SERVICE_PORT);
			log.info("RemoteDesktopServiceImpl stub: " + namingStub);
			serverStub = new MarshalledObject(namingStub);
			serverSocket = new ServerSocket(port, acceptCount, InetAddress.getByName(address));
		}
		catch (Exception e)
		{
			log.fatal(sm.getString("desktopConnector.startFailed", e));
			return;
		}

		threadDone = false;
		String threadName = "Willow DesktopService[" + toString() + "]";
		thread = new Thread(new DesktopConnectorListener(), threadName);
		thread.setDaemon(true);
		thread.start();

	}

	/**
	 * Stop the background thread that is periodically checking for
	 * session timeouts.
	 */
	protected void threadStop()
	{

		if (thread == null)
			return;

		threadDone = true;

		try
		{
			Socket s = null;
			// Need to create a connection to unlock the accept();
			if (address == null)
			{
				s = new Socket("127.0.0.1", port);
			}
			else
			{
				s = new Socket(address, port);
			}

			s.close();
		}
		catch (Exception e)
		{
			log.error("Caught exception trying to unlock accept on " + port + " " + e.toString());
		}

		try
		{
			serverSocket.close();
			UnicastRemoteObject.unexportObject(desktopServiceImpl, true);
		}
		catch (Exception e)
		{
			log.error("Caught exception trying to close socket.", e);
		}
		serverSocket = null;
		desktopServiceImpl = null;
		thread = null;
	}

	protected class DesktopConnectorListener implements Runnable
	{
		public void run()
		{
			while (!threadDone)
			{
				Socket socket = null;
				// Accept a connection
				try
				{
					socket = serverSocket.accept();
				}
				catch (IOException e)
				{
				}

				if (threadDone)
				{
					if (socket != null)
					{
						try
						{
							socket.close();
						}
						catch (Exception ex)
						{
						}
					}
					break;
				}

				new Thread(new DesktopConnectorProcessor(socket)).start();
			}
		}
	}

	protected class DesktopConnectorProcessor implements Runnable
	{
		private Socket socket;
		public DesktopConnectorProcessor(Socket socket)
		{
			this.socket = socket;
		}
		public void run()
		{
			//Return the naming server stub
			try
			{
				ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
				out.writeObject(serverStub);
			}
			catch (IOException ex)
			{
				log.error("Error writing response", ex);
			}
		}
	}

}