# Bryan Schumaker (5 / 15 / 2011)

from BaseHTTPServer import HTTPServer
import threading

from libsaria import prefs
import request

server = None
PREF_KEY="libsaria.server.enabled"
prefs.init(PREF_KEY, False)

def setup_server():
	global server
	if prefs.get(PREF_KEY) == False:
		return
	try:
		server = HTTPServer(('', 4242), request.Handler)
		server.serve_forever()
	except Exception,e:
		print "Error starting server:", e

def startup():
	threading.Thread(target=setup_server).start()
startup()

def shutdown():
	global server
	if server != None:
		server.shutdown()
		server = None

def get_state():
	return prefs.get(PREF_KEY)

def toggle_state(active):
	prefs.set(PREF_KEY, active)
	if active == True:
		startup()
	else:
		shutdown()
