/*
 * Copyright 2011 Jonathan Anderson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.footlights.ui.web;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.common.collect.Maps;

import me.footlights.core.Footlights;


/** Acts as a master server for Basic UI, JavaScript and Ajax */
public class MasterServer implements Runnable
{
	public MasterServer(int port, Footlights footlights,
		AjaxServer ajaxServer, StaticContentServer staticServer)
	{
		this.port = port;
		this.servers = Maps.newHashMap();

		servers.put("", staticServer);
		servers.put("static", staticServer);

		servers.put("ajax", ajaxServer);
	}


	public void run()
	{
		log.entering(getClass().getName(), "run");

		try
		{
			ServerSocket serverSocket = new ServerSocket(port);

			done = false;
			while (!done)
			{
				log.fine("Waiting for connection...");
				Socket socket = serverSocket.accept();
				log.fine("Accepted conncetion from " + socket);

				BufferedReader in =
					new BufferedReader(
						new InputStreamReader(
							socket.getInputStream()));

				String rawRequest = in.readLine();
				if (rawRequest == null) continue;

				Request request = Request.parse(rawRequest);
				log.info("Request: " + request.toString());

				Response response;
				try
				{
					WebServer server = servers.get(request.prefix());
					if (server == null)
						throw new FileNotFoundException(request.path());

					else response = server.handle(request.shift());
				}
				catch(FileNotFoundException e) { response = Response.error(e); }
				catch(SecurityException e) { response = Response.error(e); }
				catch(Throwable t) { response = Response.error(t); }

				if (response.isError())
					log.warning("Error handling " + request + ": " + response.statusMessage());
				else
					log.fine("Response: " + response);

				try
				{
					response.write(socket.getOutputStream());
					log.finer("Sent response: " + response);
					socket.close();
				}
				catch(SocketException e)
				{
					log.log(Level.SEVERE, "Uncaught SocketException", e);
				}
			}
		}
		catch(Exception e)
		{
			System.err.println("Web UI dying:");
			e.printStackTrace(System.err);
		}
	}


	private static final Logger log = Logger.getLogger(MasterServer.class.getName());

	private final int port;
	private boolean done;

	private final Map<String,WebServer> servers;
}

@@ -1921,31 +1921,16 @@
 sponse;%0A
-%09%09%09%09try%0A%09%09%09%09%7B%0A%09
 %09%09%09%09WebS
@@ -1983,41 +1983,116 @@
 %09%09%09%09
-%09if (server == null)%0A%09%09%09%09%09%09throw 
+log.fine(request + %22 being handler by: %22 + server);%0A%0A%09%09%09%09if (server == null)%0A%09%09%09%09%09response = Response.error(
 new 
@@ -2132,20 +2132,20 @@
 h())
+)
 ;%0A%0A
-%09
 %09%09%09%09else
  res
@@ -2140,16 +2140,27 @@
 %09%09%09%09else
+%0A%09%09%09%09%09try %7B
  respons
@@ -2198,52 +2198,56 @@
 ());
+ %7D
 %0A%09%09
-%09%09%7D%0A
 %09%09%09
-%09
 catch(
-FileNotFoundException e) %7B 
+SecurityException e)%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09
 resp
@@ -2275,76 +2275,132 @@
 (e);
- %7D
 %0A%09%09%09%09
-catch(SecurityException e) %7B response = Response.error(e); 
+%09%09log.log(Level.WARNING,%0A%09%09%09%09%09%09%09%09%22Error handling %22 + request + %22:%22 + response,%0A%09%09%09%09%09%09%09%09response.errorCause());%0A%09%09%09%09%09
 %7D%0A
+%09
 %09%09%09%09
@@ -2417,19 +2417,30 @@
 wable t)
- %7B 
+%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09
 response
@@ -2464,57 +2464,45 @@
 (t);
- %7D%0A%0A%09%09%09%09if (response.isError())%0A%09%09%09%09%09log.warning(
+%0A%09%09%09%09%09%09log.log(Level.SEVERE,%0A%09%09%09%09%09%09%09%09
 %22Err
@@ -2529,17 +2529,16 @@
 est + %22:
- 
 %22 + resp
@@ -2545,21 +2545,36 @@
 onse
-.statusMessag
+,%0A%09%09%09%09%09%09%09%09response.errorCaus
 e())
@@ -2575,30 +2575,27 @@
 use());%0A%09%09%09%09
-else%0A%09
+%09%7D%0A
 %09%09%09%09log.fine

Improve error logging in MasterServer.