# Bryan Schumaker (11/13/2010)

import libsaria
import imp
from libsaria.sources import library
from libsaria import threads
from libsaria import lastfm

__NAME__ = "Web Server"

path     = libsaria.path
exists   = path.exists
join     = path.join
sep      = path.sep
basename = path.basename
splitext = path.splitext

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

html   = join(path.cwd(), "html")
server = None
types  = {".html":"text/html", ".js":"text/javascript",
		".ico":"image/vnd.microsoft.icon",
		".png":"image/png", ".jpg":"image/jpeg",
		".py":"text/html", ".mp3":"audio/mpeg",
		".ogg":"audio/ogg"}


def format_text(text):
	text = text.replace("%20", " ")
	text = text.replace("%2F", "/")
	text = text.replace("%27", "'")
	text = text.replace("%2C", ",")
	return text

def format_path(path):
	if path == "" or path == "/":
		path = html + "/index.html"
		return path, None
	split = path.split("?", 1)
	if len(split) == 1:
		return html + path, None
	path   = split[0]
	args   = split[1].split("&")
	kwargs = {}
	for arg in args:
		split = arg.split("=", 1)
		kwargs[split[0]] = format_text(split[1])
	return html + path, kwargs


class HTTPRequest(BaseHTTPRequestHandler):

	def do_GET(self):
		try:
			fpath, args = format_path(self.path)
			#print fpath
			base, ext = splitext(fpath)
			if ext == ".py":
				self.py_file(args, fpath, base)
			elif ext == ".jpg":
				self.jpg_file(fpath)
			elif ext == ".mp3" or ext == ".ogg":
				self.audio_file()
			else:
				self.other_file(fpath, ext)
		except IOError:
			self.send_error(404, 'File Not Found: %s' % self.path)

	def do_POST(self):
		print self.path
		print "Received a post request!"

	def res_ok(self, ext):
		self.send_response(200)
		self.send_header('Content-type', '%s' % types[ext])
		self.end_headers()

	def py_file(self, kw, path, base):
		if not exists(path):
			raise IOError
		file = basename(base)
		mod = imp.load_source(file, path)
		self.res_ok(".py")
		mod.to_html(self.wfile, kw)

	def jpg_file(self, ipath):
		split = self.path.strip("/").split("/")
		if split[0] == "artwork":
			artist = format_text(split[1])
			album  = splitext(split[2])[0]
			album  = format_text(album)
			ipath = lastfm.get_artwork_tags(artist, album)
		base, ext = splitext(ipath)
		self.other_file(ipath, ext)

	def audio_file(self):
		sid, ext = splitext(self.path.strip("/"))
		fpath    = library.get_attrs(long(sid), "filepath")
		self.other_file(fpath, ext)

	def other_file(self, path, ext):
		if not exists(path):
			raise IOError
		try:
			#print "Opening: %s" % path
			f = open(path)
			self.res_ok(ext)
			self.wfile.write(f.read())
			f.close()
		except Exception,e:
			print "Error!! message: %s" % e


def start_server():
	global server
	if libsaria.__dev__ == True:
		server = HTTPServer(('', 4243), HTTPRequest)
	else:
		server = HTTPServer(('', 4242), HTTPRequest)
	server.serve_forever()

def start():
	threads.background(start_server)

def stop():
	server.shutdown()

def check_version():
	if libsaria.__major__ != 4:
		return False
	if libsaria.__minor__ == 4:
		return True
	return False

