import os, cgi, datetime, time, urllib
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import time
import datetime

from entities import Clipboard

_keys = [
 "$", "&", "+", ",", "/", ":", ";", "=", "?", "@", " ", '"',
 "<", ">", "#", "%", "{", "}", "|", "\\", "^", "~", "[", "]", "`"]

_vals = [
 '%24', '%26', '%2B', '%2C', '%2F', '%3A', '%3B', '%3D', '%3F',
 '%40', '%20', '%22', '%3C', '%3E', '%23', '%25', '%7B', '%7D',
 '%7C', '%5C', '%5E', '%7E', '%5B', '%5D', '%60']

class PostClip(webapp.RequestHandler):
	def get(self):				
		return self.response.out.write('You called this request in GET method.')
		
	def post(self):
		clip = Clipboard()

		clip.UID = self.request.get('ID')
		clip.PlainContent = db.Text(urllib.unquote(self.request.get('TextContent'))).replace('+',' ')
		clip.Type = int(self.request.get('Type'))
		clip.IsGAESync = bool(self.request.get('IsGAESync'))
		clip.Subject = (urllib.unquote(self.request.get('Subject')))
		clip.CreateDateTime = datetime.datetime.strptime(self.request.get('CreateDateTime'),'%Y-%m-%d %H:%M:%S')
		clip.CreateBy = self.request.get('CreateBy')

		clip.put()
		
		return self.response.out.write('Clip has been put in correct.')
		
class ClipView(webapp.RequestHandler):
	def get(self):
		offset = self.request.get('offset')
		
		if not offset:
			offset = 0
		
		if users.get_current_user().__str__().upper() != 'kisflying'.upper():
			return self.redirect(users.create_login_url('/clipboard/'))		
		
		count = Clipboard.all().count() 
		clips = Clipboard.all().order('-CreateDateTime').fetch(50,int(offset))
		
		template_values = {'clips':clips, 'count': count}
		
		path = os.path.join(os.path.dirname(__file__), 'templates/clipboard.html')
		self.response.out.write(template.render(path, template_values))
		
class DeleteClip(webapp.RequestHandler):		
	def get(self):
		if self.request.get('key'):
			clip = db.get(db.Key(self.request.get('key')))
			
			if clip: clip.delete()
				
		return self.redirect('/clipboard/')

application = webapp.WSGIApplication([('/clipboard/postclip', PostClip), ('/clipboard/', ClipView), ('/clipboard/delclip', DeleteClip)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()