#Copyright (c) 2008 Mike Chambers
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.

import cgi
import wsgiref.handlers

import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

#requires Python Pygments library
#http://pygments.org/

class Format(webapp.RequestHandler):
	
	#This handles all POST requests
	def post(self):
  
  		#get the output variable
  		output = self.request.get('output');
  		
  		#if it is not HTML then use XML
  		if(output != 'html'):
  			output = 'xml'
  	
  		#get language variable to find out what language
  		#the code is in
		language = self.request.get('language');
		
		#trim before check?
		
		#make sure that it is not empty
		if language == '':
			#if empty return an error
			self.sendError("language must be specified", output)
			return
			
		#get the code
		source = self.request.get('source')
  	
  		#trim before check?
  		#make sure code is not empty
		if source == '':
			#if empty return an error
			self.sendError("source must be specified", output)
			return  	
			
		#get the lexer for the language
  		try:
			lexer = get_lexer_by_name(language)
		except:
			#if any errors occur, send an error
			self.sendError("Unknown language", output)
			return 	

		#get the formatter
		formatter = HtmlFormatter(linenos=False, noclasses=True)

		try:
			#try and format it
			formatted_code = highlight(source, lexer, formatter) 
		except:
			#if anything goes wrong, send an error
			self.sendError("Could not format input", output)
			return
		
		#pick the correct template depending on the output type
		if output == 'html':
			template_name = 'templates/html.template'
		else:
			template_name = 'templates/xml.template'	
		
		#create the data for the template
		template_values = {'formatted_code':formatted_code,
							'language':language,}
		
		#write out the template
		path = os.path.join(os.path.dirname(__file__), template_name)
		self.response.out.write(template.render(path, template_values))

	#method that sends and error
	#message - error message
	#output - html or xml (default) that specifies the output type
	def sendError(self, message, output):
	
		if output=='html':
			template_name = 'templates/html.error.template'
		else:
			template_name = 'templates/xml.error.template'
		
		template_values = {'message':message,}

		path = os.path.join(os.path.dirname(__file__), template_name)
		self.response.out.write(template.render(path, template_values))


def main():
	application = webapp.WSGIApplication(
                                 [('/doformat', Format)],
                                       debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()