import models
import library
import logging
import datetime

from google.appengine.ext import db

def getUserIDfromObject(obj):
	if obj == None:
		return
	
	#logging.info("getUserIDfromObject: obj.key().id() = " + str(obj.user_object.key().id()))
	return obj.user_object.key().id()

class UserAccount():
	LOGGED_IN = 0
	user_object = None
	USER_COOKIE_KEY = "landfilproject"

	def incrementUserScore(self, u_id):
		#TODO:
		return "OK"
		
	def decrementUserScore(self, u_id):
		#TODO:
		return "OK"
		
	def getUsername(self):
		if self.user_object == None:
			logging.info("Logging info = None")
			return ''
		else:
			#logging.info("Returning username: " + self.user_object.username)
			return self.user_object.username
	
	def validatePassword(self, password):
		if self.user_object != None:
			return 
		
		return False
		
	def queryUsername(self, username):
		userlist = db.GqlQuery("SELECT * from UserAccountModel WHERE username = '" + username + "'")
		if userlist.count(limit=1):
			user = userlist[0]
		else:
			#logging.info("queryUsername: User not found")
			user = None
		
		return user
	
	def LogoutUser(self):
		if self.user_object == None:
			return 
			
		logging.info("Setting LOGGED_IN to 0")
		self.LOGGED_IN = 0
		expires = datetime.datetime.now() + datetime.timedelta(weeks=-52)
		logging.info("Setting cookie to expire at " + str(expires))
		expiresStr = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
		
		# Now put it all together
		cookieStr = self.USER_COOKIE_KEY + '= ' + ';expires=' + expiresStr
		return cookieStr


	def LoginUser(self):
		#logging.info("Logging in user " + self.user_object.username)
		self.LOGGED_IN = 1
		
	def validateUser(self, username, password):
		if self.user_object == None:
			return False
		# check if the username was set.
		if self.user_object.username == '' or self.user_object.password_hash == '':
			return False
		
		#logging.info("validateUser: username: " + username + " password: " + password)
		result = library.valid_pw(username, password, self.user_object.password_hash)
		#logging.info("result = " + str(result))
		return result

	def registerUser(self, uname, pword):
			if not self.usernameExists(uname):
				u = models.UserAccountModel(username = uname,
				password_hash = library.make_pw_hash(uname, pword), score = 0)
			
				u.put()
				return "OK"
			else:
				return "Username Already Exists"
	
	def loadUserAccount(self, u):
		#logging.info("loadUserAccount: loading user account: " + u)
		self.user_object = self.queryUsername(u)
		
		return self.user_object != None
	
	def usernameExists(self, username):
		# just attempt to load the user account again
		return self.loadUserAccount(username)

	def createUserCookie(self, remember):
		# sanity check
		if self.user_object == None:
			return ""
			
		#logging.info("Looking to see what type of cookie to create")
		if remember == "yes":
			#logging.info("Creating long term cookie")
			# They do, so set a cookie to remember login for 1 year.
			expires = datetime.datetime.now() + datetime.timedelta(weeks=52)
		else:
			#logging.info("Creating short term cookie")
			# They don't, so set a cookie to expire now, so the website won't remember them.
			expires = None
		
		# create a hash for the username
		hash_str = str(library.make_hash_str(self.user_object.username))

		if expires is not None:
			# Format the expire timestamp.
			expiresStr = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
			cookieStr = self.USER_COOKIE_KEY + '=' + hash_str + ';expires=' + expiresStr
		else:
			cookieStr = self.USER_COOKIE_KEY + '=' + hash_str 
		
		#logging.info("createUserCookie returning: " + cookieStr)
		return cookieStr

	def queryUsernameByID(self, id):
		user = getUserByID(id) 
		if user != None:
			return user.user_object.username
		else:
			return ""
			
		return ""
		
	def getUserByID(self, id):
		userlist = db.GqlQuery("SELECT * FROM UserAccountModel WHERE __key__ = KEY('UserAccountModel', " + str(id))
		if userlist.count(limit=1):
			#logging.info("getUserByID successful")
			return userlist[0]
		else:
			#logging.info("getUserByID failed")
			return None
		
		return None
	
	def getUserID(self):
		if self.user_object == None:
			return ""
		#logging.info("user_object.key().id() = " + str(self.user_object.key().id()))
		return self.user_object.key().id()
		
