package de.skyrix.zsp.logic.httpserver;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TimeZone;

import sun.misc.BASE64Decoder;
import de.skyrix.zsp.conf.ZSPConfig;
import de.skyrix.zsp.logic.Proxy;
import de.skyrix.zsp.logic.httpclient.HttpResponse;

/**Server for HTTP/DAV queries.
 * 
 * @author Burkhard Sell
 * @author derived from NANO-HTTPD
 */
public class HttpServer {
	/**Flag to show if abort is requested*/
	private boolean canceled = false;

	/**Container for registered MethodModules*/
	private static Hashtable methodModules = null;

	/**TCP Port to listen to*/
	private int tcpPort;

	/**GMT date formatter*/
	private static java.text.SimpleDateFormat gmtFormatter;
	static {
		gmtFormatter =
			new java.text.SimpleDateFormat(
				"E, d MMM yyyy HH:mm:ss 'GMT'",
				Locale.US);
		gmtFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	/**Starts a HTTP server listening to given port
	 * 
	 * @throws IOException if the socket is already in use
	 */
	public HttpServer() throws IOException {
		tcpPort = 23000;
		try {
			tcpPort = Integer.parseInt(ZSPConfig.getProperty("proxy_port"));
		}
		catch (Exception e) {
		}

		final ServerSocket ss = new ServerSocket(tcpPort);
		//ss.setSoTimeout(5000);
		Thread t = new Thread(new Runnable() {
			public void run() {
				while (!canceled) {
					try {
						System.out.println(" waiting for connection");
						new HTTPSession(ss.accept());
					}
					catch (Exception i) {
					}
				}
			}
		});
		//t.setDaemon(true);
		t.start();
		//t.run();
	}

	/**Register a <code>MethodModule</code> the handle queries
	 * for a defined HTTP/DAV method. 
	 * 
	 * @param module - the module
	 * 
	 * @return the previously registered module for this method, if any
	 * @throws IllegalArgumentException if getMethodName
	 *         of the module returns <code>null</code>.
	 */
	public static MethodModule registerOptionModule(MethodModule module) {
		if (module == null)
			return null;
		String methodName = module.getMethodName();

		if (methodName == null)
			throw new IllegalArgumentException("Invalid MethodModule given, getMethodName returned null.");

		methodName = methodName.toUpperCase();

		if (methodModules == null)
			methodModules = new Hashtable();

		MethodModule oldModule = null;
		try {
			oldModule = (MethodModule) methodModules.get(methodName);
			if (!(oldModule instanceof MethodModule))
				oldModule = null;
		}
		catch (Exception e) {
		}

		methodModules.put(methodName, module);

		return oldModule;
	}

	/*private void printProp(Properties prop) {
		//System.out.print("Properties: ");
		if (prop == null) {
			return;
		}

		System.out.println(prop.entrySet().size() + " elements");

		Enumeration keyEnumeration = prop.keys();
		while (keyEnumeration.hasMoreElements()) {
			String key = (String) keyEnumeration.nextElement();
			String value = prop.getProperty(key);
			System.out.println(key + " --> " + value);
		}
	}*/

	/**
	 * Override this to customize the server.<p>
	 * 
	 * (By default, this delegates to serveFile() and allows directory listing.)
	 * 
	 * @parm uri	Percent-decoded URI without parameters, for example "/index.cgi"
	 * @parm method	"GET", "POST" etc.
	 * @parm parms	Parsed, percent decoded parameters from URI and, in case of POST, data.
	 * @parm header	Header entries, percent decoded
	 * @return HTTP response, see class Response for details
	 */
	public Response serve(
		String uri,
		String method,
		Properties header,
		Properties parms,
		String body) {

		//System.out.println("request is: ");
		//System.out.println(method + " '" + uri + "' ");
		//System.out.print("header --> ");
		//printProp(header);

		//set proxy authorization key
		if ("true".equals(ZSPConfig.getProperty("detectAuthKey"))) {
			String authKey = header.getProperty("Authorization", null);
			if (authKey != null && !"".equals(authKey.trim())) {
				System.setProperty("zsp.ProxyAuthKey", authKey);

				try {
					StringTokenizer authKeyTokenizer = new StringTokenizer(authKey, " ");
					//ignore first token
					String dummy = authKeyTokenizer.nextToken();

					//second token should contain encoded user:password
					//so decode it and get the user and password token
					StringTokenizer decodedTokenizer =
						new StringTokenizer(
							new String(
								new BASE64Decoder().decodeBuffer(
									authKeyTokenizer.nextToken())),
							":");

					String userName = decodedTokenizer.nextToken();
					String password = decodedTokenizer.nextToken();
					ZSPConfig.setProperty("zidestore_user", userName);
					ZSPConfig.setProperty("zidestore_password", password);

				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		if (methodModules != null) {
			try {
				MethodModule module =
					(MethodModule) methodModules.get(method.toUpperCase());
				return module.processQuery(uri, header, parms, body);
			}
			catch (Exception e) {
			}
		}

		//System.out.println("no module found...trying to loop through");

		try {
			HttpResponse httpResponse = null;
			if (Proxy.isOnline()) {
				httpResponse =
					Proxy.getInstance().loopThrough(uri, method, header, body);
			}

			if (httpResponse != null) {
				//System.out.println(httpResponse.getHeaders());
				Response response =
					new Response(
						"" + httpResponse.getStatusCode(),
						HttpServer.MIME_HTML,
						httpResponse.getBody());

				response.addHeaders(httpResponse.getHeaders());

				return response;
			}
			else
				return new Response(
					HttpServer.HTTP_NOTIMPLEMENTED,
					HttpServer.MIME_HTML,
					"");
		}
		catch (Exception e) {
			e.printStackTrace();
			return new Response(
				HTTP_INTERNALERROR,
				MIME_HTML,
				"An exception raised:" + e.getMessage());
		}
	}

	/**
	 * Some HTTP response status codes
	 */
	public static final String HTTP_OK = "200 OK",
		HTTP_REDIRECT = "301 Moved Permanently",
		HTTP_AUTHORIZATION = "401 Authorization Required",
		HTTP_FORBIDDEN = "403 Forbidden",
		HTTP_NOTFOUND = "404 Not Found",
		HTTP_BADREQUEST = "400 Bad Request",
		HTTP_INTERNALERROR = "500 Internal Server Error",
		HTTP_NOTIMPLEMENTED = "501 Not Implemented";

	/**
	 * Common mime types for dynamic content
	 */
	public static final String MIME_PLAINTEXT = "text/plain",
		MIME_HTML = "text/html",
		MIME_DEFAULT_BINARY = "application/octet-stream";

	/**
	 * Handles one session, i.e. parses the HTTP request
	 * and returns the response.
	 */
	private class HTTPSession implements Runnable {
		public HTTPSession(Socket s) {
			mySocket = s;
			Thread t = new Thread(this);
			t.setDaemon(true);
			t.start();
			//t.run();
		}

		public void run() {
			try {
				InputStream is = mySocket.getInputStream();
				if (is == null)
					return;
				BufferedReader in = new BufferedReader(new InputStreamReader(is));

				// Read the request line
				StringTokenizer st = new StringTokenizer(in.readLine());
				if (!st.hasMoreTokens())
					sendError(
						HTTP_BADREQUEST,
						"BAD REQUEST: Syntax error. Usage: GET /example/file.html");

				String method = st.nextToken();

				if (!st.hasMoreTokens())
					sendError(
						HTTP_BADREQUEST,
						"BAD REQUEST: Missing URI. Usage: GET /example/file.html");

				String uri = decodePercent(st.nextToken());

				// Decode parameters from the URI
				Properties parms = new Properties();
				int qmi = uri.indexOf('?');
				if (qmi >= 0) {
					decodeParms(uri.substring(qmi + 1), parms);
					uri = decodePercent(uri.substring(0, qmi));
				}

				// If there's another token, it's protocol version,
				// followed by HTTP headers. Ignore version but parse headers.
				Properties header = new Properties();
				if (st.hasMoreTokens()) {
					String line = in.readLine();
					while (line.trim().length() > 0) {
						int p = line.indexOf(':');
						header.put(
							line.substring(0, p).trim(),
							line.substring(p + 1).trim());
						line = in.readLine();
					}
				}

				// If the method is POST, there may be parameters
				// in data section, too, read another line:
				if (method.equalsIgnoreCase("POST"))
					decodeParms(in.readLine(), parms);

				//System.out.println("request body is: ");

				String body = "";
				String line = null;
				while (in.ready()) {
					line = in.readLine();
					if (line != null)
						body += line;
					//System.out.println(line);
				}

				//System.out.println("header: " + header);

				if (!header.containsKey("Authorization")) {
					Response response = new Response();
					response.addHeader("www-authenticate", "basic realm=\"SKYRiX\"");
					response.addHeader("content-length", "0");

					sendResponse(
						HTTP_AUTHORIZATION,
						MIME_PLAINTEXT,
						response.header,
						null);
					in.close();
					return;
				}

				if ("".equals(body))
					body = null;

				//System.out.println("body = " + body);

				// Ok, now do the serve()
				Response r = serve(uri, method, header, parms, body);
				//System.out.println(r.header);
				if (r == null)
					sendError(
						HTTP_INTERNALERROR,
						"SERVER INTERNAL ERROR: Serve() returned a null response.");
				else
					sendResponse(r.status, r.mimeType, r.header, r.data);

				in.close();
			}
			catch (IOException ioe) {
				try {
					sendError(
						HTTP_INTERNALERROR,
						"SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
				}
				catch (Throwable t) {
				}
			}
			catch (InterruptedException ie) {
				// Thrown by sendError, ignore and exit the thread.
			}
		}

		/**
		 * Decodes the percent encoding scheme. <br/>
		 * For example: "an+example%20string" -> "an example string"
		 */
		private String decodePercent(String str) throws InterruptedException {
			try {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < str.length(); i++) {
					char c = str.charAt(i);
					switch (c) {
						case '+' :
							sb.append(' ');
							break;
						case '%' :
							sb.append(
								(char) Integer.parseInt(str.substring(i + 1, i + 3), 16));
							i += 2;
							break;
						default :
							sb.append(c);
							break;
					}
				}
				return new String(sb.toString().getBytes());
			}
			catch (Exception e) {
				sendError(HTTP_BADREQUEST, "BAD REQUEST: Bad percent-encoding.");
				return null;
			}
		}

		/**
		 * Decodes parameters in percent-encoded URI-format
		 * ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
		 * adds them to given Properties.
		 */
		private void decodeParms(String parms, Properties p)
			throws InterruptedException {
			if (parms == null)
				return;

			StringTokenizer st = new StringTokenizer(parms, "&");
			while (st.hasMoreTokens()) {
				String e = st.nextToken();
				int sep = e.indexOf('=');
				if (sep >= 0)
					p.put(
						decodePercent(e.substring(0, sep)).trim(),
						decodePercent(e.substring(sep + 1)));
			}
		}

		/**
		 * Returns an error message as a HTTP response and
		 * throws InterruptedException to stop furhter request processing.
		 */
		private void sendError(String status, String msg)
			throws InterruptedException {
			sendResponse(
				status,
				MIME_PLAINTEXT,
				null,
				new ByteArrayInputStream(msg.getBytes()));
			throw new InterruptedException();
		}

		/**
		 * Sends given response to the socket.
		 */
		private void sendResponse(
			String status,
			String mime,
			Properties header,
			InputStream data) {

			boolean debug = false;

			try {
				if (status == null)
					throw new Error("sendResponse(): Status can't be null.");

				//if (debug)
				//	System.out.println("Response is:");

				OutputStream out = mySocket.getOutputStream();
				PrintWriter pw = new PrintWriter(out);
				pw.print("HTTP/1.0 " + status + " \r\n");
//				if (debug)
//					System.out.print("HTTP/1.0 " + status + " \r\n");

				if (mime != null) {
					pw.print("Content-Type: " + mime + "\r\n");
//					if (debug)
//						System.out.print("Content-Type: " + mime + "\r\n");
				}

				if (header == null || header.getProperty("Date") == null) {
					pw.print("Date: " + gmtFormatter.format(new Date()) + "\r\n");
//					if (debug)
//						System.out.print(
//							"Date: " + gmtFormatter.format(new Date()) + "\r\n");
				}

				if (header != null) {
					Enumeration e = header.keys();
					while (e.hasMoreElements()) {
						String key = (String) e.nextElement();
						String value = header.getProperty(key);
						pw.print(key + ": " + value + "\r\n");
//						if (debug)
//							System.out.print(key + ": " + value + "\r\n");
					}
				}

				pw.print("\r\n");
//				if (debug)
//					System.out.print("\r\n");
				pw.flush();

				if (data != null) {
					byte[] buff = new byte[2048];
					int read = 2048;
					while (read == 2048) {
						read = data.read(buff, 0, 2048);
						out.write(buff, 0, read);
						System.out.write(buff, 0, read);
					}
				}
				out.flush();
				out.close();
				if (data != null)
					data.close();
			}
			catch (Exception e) {
				// Couldn't write?
				try {
					mySocket.close();
				}
				catch (Throwable t) {
				}
			}
//			if (debug)
//				System.out.println();
		}

		private Socket mySocket;
		private BufferedReader myIn;
	};

	/**
	 * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
	 */
	private static Hashtable theMimeTypes = new Hashtable();
	static {
		StringTokenizer st =
			new StringTokenizer(
				"htm		text/html "
					+ "html		text/html "
					+ "txt		text/plain "
					+ "asc		text/plain "
					+ "gif		image/gif "
					+ "jpg		image/jpeg "
					+ "jpeg		image/jpeg "
					+ "png		image/png "
					+ "mp3		audio/mpeg "
					+ "m3u		audio/mpeg-url "
					+ "pdf		application/pdf "
					+ "doc		application/msword "
					+ "ogg		application/x-ogg "
					+ "zip		application/octet-stream "
					+ "exe		application/octet-stream "
					+ "class		application/octet-stream ");
		while (st.hasMoreTokens())
			theMimeTypes.put(st.nextToken(), st.nextToken());
	}
}
