# -*- coding: UTF-8 -*-

import cgi
import httplib
import socket
import time
from threading import Thread
from Queue import Queue
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class HttpServer(HTTPServer):

	# HttpServer status
	STATUS_INIT    = 0
	STATUS_RUNNING = 1
	STATUS_STOP    = 2
	STATUS_ERROR   = 3
	
	# By default, request_queue_size is 5. Up to 255.
	request_queue_size = 255
	t_print_log = time.time()
	
	def __init__(self, dialogInterfaces):
		self.dialogInterfaces = dialogInterfaces
		# self.session_manager = '192.168.102.36'#Config.session_manager
		self.tcp_port = 80#Config.SLAVE_SERVER_PORT
		self.status = HttpServer.STATUS_INIT
		self.serverHasBeLanched = False
		self.spooler = Queue()
		self.threadNumber = 5

	def initialize(self):
		try:
			HTTPServer.__init__(self, ("", self.tcp_port), HttpRequestHandler)
			
			# Handle request threads
			self.threads = []
			for _ in xrange(self.threadNumber):
				t = Thread(name = "HTTPRequestHandler", target = self.thread_run)
				#t.setDaemon(True)   #
				self.threads.append(t)
				t.start()
		except socket.error, e:
			#Logger.error("Unable to initialize HttpServer: %s"%(str(e)))
			return False
		
		return True
		
	# Auto called to dispatch request
	def process_request(self, request, client_address):
		print client_address
		# client_address = (self.session_manager, self.tcp_port)
		self.spooler.put((request, client_address))
		
	# Request handle thread run 
	def thread_run(self):
		while True:
			(request, client_address) = self.spooler.get()
			print (request, client_address)
			#Modified by wangshigang to verify the center IP
			# if Config.session_manager == client_address[0]:
			self.process_request_thread(request, client_address)
	
	def process_request_thread(self, request, client_address):
		try:
			print request
			self.finish_request(request, client_address)
		except socket.error, (code, msg):
			(addr, port) = client_address
			#Logger.debug("HTTPServer: %s (%s, %s)" % (msg, addr, port))
		except Exception, e:
			#Logger.debug("HTTPServer: unknown exception %s: %s" % (type(e), e))
			pass
		finally:
			self.close_request(request)

	def run(self):
		print 'run'
		self.status = HttpServer.STATUS_RUNNING
		self.serverHasBeLanched = True
		HTTPServer.serve_forever(self)
		self.status = HttpServer.STATUS_STOP
	
	def stop(self):
		if self.serverHasBeLanched:
			try:
				HTTPServer.shutdown(self)
			except Exception, err:
				# with python 2.5 shutdown does not exist
				pass
			
			HTTPServer.server_close(self)
		
		for t in self.threads:
			if t.isAlive():
				t._Thread__stop()
		
		time.sleep(3)
		for t in self.threads:
			if t.isAlive():
				t._Thread__delete()

	def process(self, request):
		t_print_temp = time.time()
		if t_print_temp - HttpServer.t_print_log > 30:
			#Logger.debug("http thread is running")
			HttpServer.t_print_log = time.time()
		print request["path"]
		
		return self.dialogInterfaces.process(request)
		
		#Logger.warn("Unknown domain for request %s"%(str(request)))
		return None	
	
	def getStatus(self):
		return self.status


class HttpRequestHandler(SimpleHTTPRequestHandler):
	def log_message(self, format, *args):
		""" Override the parent log function"""
		pass
		
	def log_error(self, format, *args):
		""" Override the parent log function"""
		#Logger.debug("HTTPRequestHandler Error: %s"%(format%args))
	
	# override do_GET
	def do_GET(self):
		req = {}
		req["client"] = self.client_address[0]
		req["method"] = "GET"
		req["domain"] = self.path.split("/", 2)[1]
		
		req["path"] = self.path
		req["args"] = {}
		
		if "?" in self.path:
			req["path"], args = self.path.split("?", 1)
			
			args = cgi.parse_qsl(args)
			for (k,v) in args:
				req["args"][k] = v
	
		response = self.server.process(req)
		if response is None:
			self.send_error(httplib.NOT_FOUND)
			return
		if response is False:
			self.send_error(httplib.UNAUTHORIZED)
			return
		
		self.send_response(httplib.OK)
		self.send_header("Content-Type", response["Content-Type"])
		self.end_headers()
		self.wfile.write(response["data"])
	
	# override do_POST
	def do_POST(self):
		req = {}
		req["client"] = self.client_address[0]
		req["method"] = "POST"
		
		req["path"] = self.path
		req["args"] = {}
				
		length = int(self.headers["Content-Length"])
		if length > 0:
			req["data"] = self.rfile.read(length)
			
		response = self.server.process(req)
		if response is None:
			self.send_error(httplib.NOT_FOUND)
			return
		
		self.send_response(httplib.OK)
		self.send_header("Content-Type", response["Content-Type"])
		self.end_headers()
		self.wfile.write(response["data"])

if __name__ == "__main__":
	from Dialog import ( ExtendDialog)

	extendDialog = ExtendDialog()
	httpServer=HttpServer(extendDialog)
	
	httpServer.initialize()
	
	comm_thread = Thread(name="HttpServer", target=httpServer.run)
	#comm_thread.setDaemon(True)
	comm_thread.start()


	while True:
		cmd = raw_input("===:")
		if cmd == "exit":
			httpServer.stop()
			break