def _doGet(self):
		try:

			PM = QRzarPlayerMapper()

			if self.arg is not None:
				if self.arg.isdigit():
					# Get the user by ID
					player = PM.find(self.arg)
				else:
					raise BadRequest("Players must be requested by ID")

				if player is not None:
					return self._response(Depth.build(player, self.depth), CODE.OK)
				else:
					raise NotFound("This player does not exist")

			else:

				offset = 0
				players = PM.findAll(offset, offset+50)

				if players is None:
					raise NotFound("There are no players on this system.")

				playerslist = []
				for player in playerslist:
					playerslist.append(Depth.build(player, self.depth))

				playerslist = {"players": playerslist, "pagination_offset": offset, "max_perpage": 50}

				return self._response(playerslist, CODE.OK)

		except mdb.DatabaseError, e:
				raise ServerError("Unable to search the player database (%s: %s)" % e.args[0], e.args[1])
def main():
	from Networking.protocolhandler import ProtocolHandler
	from Common.config import TopHatConfig

	#setup the config
	TopHatConfig(path="/home/specialk/Dev/tophat/config.py")

	from Model.Mapper.qrzargamemapper import QRzarGameMapper
	from Model.Mapper.usermapper import UserMapper

	# get
	UM = UserMapper()
	user = UM.find(1)

	GM = QRzarGameMapper()
	game = GM.find(1)

	# build
	from Model.depth import Depth
	import pprint

	dic = Depth.build(user, 3)
	pprint.pprint(dic)

	print ""
	print "***********************************************"
	print ""

	dic = Depth.build(game, 3)
	pprint.pprint(dic)
	def _doGet(self):
		try:
			
			KM = KillMapper()
			
			if self.arg is not None:
				if self.arg.isdigit():
					# Get the user by ID
					kill = KM.find(self.arg)
				else:
					raise BadRequest("Kill must be requested by ID")

				if kill is not None:
					return self._response(Depth.build(kill, self.depth), CODE.OK)
				else:
					raise NotFound("This kill does not exist")
			
			else:
				offset = 0
				kills = KM.findAll(offset, offset+50)

				killslist = []
				for kill in kills:
					killslist.append(Depth.build(kill, self.depth))

				killdict = {"kills": killslist, "pagination_offset": offset, "max_perpage": 50}

				return self._response(killdict, CODE.OK)

		except mdb.DatabaseError, e:
				raise ServerError("Unable to search the kill database (%s: %s)" % e.args[0], e.args[1])
	def _doPost(self, dataObject):
		if "name" and "game" and "qrcode" in dataObject:
			if "id" not in dataObject["game"]:
				raise BadRequest("Argument provided for this game type is invalid.")

			reference_code = dataObject["qrcode"][:1]
			qr_code = dataObject["qrcode"]
			try:
				
				team = TeamMapper().findByGameIdAndCode(dataObject["game"]["id"], reference_code)

				if team is None:
					raise NotFound("The specified game id with the QRcode was not found on the server.")

				if QRzarPlayerMapper().getPlayerByQrcode(team.getGame(),qr_code ) is not None:
					raise Conflict("Your QR code is in use in this game: %s." % qr_code)


			except mdb.DatabaseError, e:
				raise ServerError("Unable to search the teams or players database (%s)" % e.args[1])

			if team is None:
				raise NotFound("Unable to find team to add player to. Check your qrcode setup.")

			player = QRzarPlayer()
			player.setName(dataObject["name"])
			player.setQRCode(qr_code)
			player.setUser(self.user)
			team.addPlayer(player)

			QRzarPlayerMapper().insert(player)

			return self._response(Depth.build(player, self.depth), CODE.CREATED)
	def _doPost(self, dataObject):
		if "email" in dataObject and "password" in dataObject:

			username = dataObject['email']
			password = dataObject['password']

			try:
				umapper = UserMapper()
				selectedUser = umapper.getUserByEmail(username)
			except mdb.DatabaseError, e:
				raise ServerError("Unable to search the user database (%d: %s)" % e.args[0], e.args[1])

			# check we have a result
			if selectedUser is None:
				raise NotFound("We have no record of a user with the username %s" % username)

			# check password is correct	return corresponding key
			if not checkHash(password, selectedUser.getPassword()):
				raise Unauthorised("Failed to login with that username and password")

			# get API token from the database and return it
			try:
				rdata = {}
				ATM_ = ApitokenMapper()
				
				rdata["apitoken"] = ATM_.findTokenByUserId(selectedUser.getId()).getToken()
				rdata["user"] = Depth.build(selectedUser, 1)

				return self._response(rdata, CODE.CREATED)

			except mdb.DatabaseError, e:
				raise ServerError("Unable to get API key from the database (%d: %s)" % e.args[0], e.args[1])
	def _doPut(self, dataObject):

		# The game creation should have no arguments.
		if self.arg is None:
			raise BadRequest("An ID must be supplied in order to update a game.")

		if "name" in dataObject:
			try:
				GM = QRzarGameMapper()

				if self.arg.isdigit():
					# Get the user b ID
					game = GM.find(self.arg)
				else:
					raise BadRequest("Games must be requested by ID")

				if game is None:
					raise NotFound("There is no game identified by the number %s" % self.arg)

				# check user has the priviledges
				if not self.user.getId() == game.getCreator().getId() and not self.user.accessLevel('super_user'):
					raise Forbidden("You do not have sufficient privileges to delete this game.")

				game.setName(dataObject["name"])

				return self._response(Depth.build(game, self.depth), CODE.CREATED)
				
			except mdb.DatabaseError, e:
				raise ServerError("Unable to search the user database (%s)" % e.args[1])
	def _doPost(self, dataObject):

		# The game creation should have no arguments.
		if self.arg is not None:
			return self._response({}, CODE.UNIMPLEMENTED)

		if "name" in dataObject:	
			GM = QRzarGameMapper()

			game = QRzarGame()

			game.setName(dataObject["name"])

			if "start_time" in dataObject:
				#Format 2012-11-07 12:53:51
				game.setStartTime(datetime.strptime(dataObject["start_time"], "%Y-%m-%d %H:%M:%S"))

			if "end_time" in dataObject:
				game.setEndTime(datetime.strptime(dataObject["end_time"], "%Y-%m-%d %H:%M:%S"))

			game.setCreator(self.user)

			try:
				GM.insert(game)			
			except mdb.DatabaseError, e:
				raise ServerError("Unable to create the game in the database (%s)" % e.args[1])

			return self._response(Depth.build(game, self.depth), CODE.CREATED)
	def _doPut(self, dataObject):

		if "name" in dataObject or "email" in dataObject or "photo" in dataObject:
			try:

				UM = UserMapper()

				if self.arg.isdigit():
					# Get the user by ID
					user = UM.find(self.arg)
				else:
					# Get the user by E-mail
					user = UM.getUserByEmail(self.arg)

				if user is not None:
					if self.user.getId() is user.getId() or self.user.accessLevel("super_user"):
						if "name" in dataObject:
							user.setName(dataObject["name"])
						
						if "email" in dataObject:
							user.setEmail(dataObject["email"])

						if "photo" in dataObject:
							user.setPhoto(dataObject["photo"])

						UserMapper.update(user)

						return self._response(Depth.build(user, self.depth), CODE.CREATED)
					else:
						raise Forbidden()
				else:
					raise NotFound("This user does not exist")
				
			except mdb.DatabaseError, e:
				raise ServerError("Unable to search the user database (%s)" % e.args[1])
	def _doPut(self, dataObject):

		if  "id" in dataObject:
			try:

				PM = QRzarPlayerMapper()

				if type(dataObject["id"]) is int:
					# Get the user by ID

					player = PM.find(dataObject["id"])

					if player is None:
						raise NotFound("The specified player type does not exist.")
				else:
					raise BadRequest("Argument provided for this player type is invalid.")

				player_user_id= player.getUser().getId()
				authenticated_user_id = self.user.getId()


 				if player_user_id == authenticated_user_id or self.user.accessLevel('super_user'):

					if dataObject.has_key("respawn_code"):

						if dataObject["respawn_code"] == player.getTeam().getRespawnCode() or self.user.accessLevel('super_user'):
							player.setAlive(True)

						else:
							raise Forbidden("Incorrect respawn QRcode")

					if "name" in dataObject:
						player.setName(dataObject["name"])

					if "latitude" in dataObject:
						player.setLat(dataObject["latitude"])

					if "longitude" in dataObject:
						player.setLon(dataObject["longitude"])

					if "flashed" in dataObject and "degree" in dataObject:
							player.setFlashed(dataObject["flashed"], dataObject["degree"])



					PM.update(player)

				return self._response(Depth.build(player, self.depth), CODE.CREATED)

			except mdb.DatabaseError, e:
				raise ServerError("Unable to search the player database (%s)" % e.args[1])
	def _doGet(self):
		try:
			UM = UserMapper()

			if self.arg is not None:

				if self.arg.isdigit():
					# Get the user by ID
					user = UM.find(self.arg)
				else:
					# Get the user by E-mail
					user = UM.getUserByEmail(self.arg)

				if user is None:
					raise NotFound("This user does not exist")

				if self.user.accessLevel("super_user") or self.user.getId() == user.getId():
					return self._response(Depth.build(user, self.depth), CODE.OK)
				else:
					raise Forbidden()

			else:
				if self.user.accessLevel("super_user"):
					offset = 0
					users = UM.findAll(offset, offset+50)

					userslist = []
					for user in users:
						userslist.append(Depth.build(user, self.depth))

					userslist = {"users": userslist, "pagination_offset":offset, "max_perpage": 50}

					return self._response(userslist, CODE.OK)
				else:
					raise Forbidden()

		except mdb.DatabaseError, e:
			raise ServerError("Unable to search the user database (%s: %s)" % (e.args[0], e.args[1]))
	def _doGet(self):
		try:
			
			GM = QRzarGameMapper()
			
			if self.arg is not None:
				if self.arg.isdigit():
					# Get the user by ID
					game = GM.find(self.arg)
				elif self.arg == "types":
					return self._response({}, CODE.UNIMPLEMENTED)
				else:
					raise BadRequest("Games must be requested by ID")

				if game is not None:
					return self._response(Depth.build(game, self.depth), CODE.OK)
				else:
					raise NotFound("There is no game identified by the number %s" % self.arg)
			
			else:

				offset = 0
				games = GM.findAll(offset, offset+50)

				if games is None:
					raise NotFound("There are no games on this system.")

				gameslist = []
				for game in games:
					gameslist.append(Depth.build(game, self.depth))

				gamedict = {"games":gameslist, "pagination_offset":offset, "max_perpage": 50}

				return self._response(gamedict, CODE.OK)

		except mdb.DatabaseError, e:
			raise ServerError("Unable to search the game database (%s: %s)" % e.args[0], e.args[1])
    def _doGet(self):
        try:

            TM = TeamMapper()

            if self.arg is not None:
                if self.arg.isdigit():
                    # Get the user by ID
                    team = TM.find(self.arg)
                else:
                    raise BadRequest("Teams must be requested by ID")

                if team is not None:
                    return self._response(Depth.build(team, self.depth), CODE.OK)
                else:
                    raise NotFound("There is no team identified by the number %s" % self.arg)

        except mdb.DatabaseError, e:
            raise ServerError("Unable to search the game database (%s: %s)" % e.args[0], e.args[1])
			blank = User()
			blank.setToken(token)
			token.setUser(blank)

			umapper = UserMapper()
			ATM = ApitokenMapper()

			blank.setRegistered(False)

			# Save changes to user
			try:
				umapper.insert(blank)

			# handle the possibility the user already exists
			except mdb.IntegrityError, e:
				raise Conflict(CODE.CONFLICT, "A unexpected conflict occurred when trying to create your anonymous login token.")

			# handle all other DB errors
			except mdb.DatabaseError, e:
				raise ServerError("Unable to create user in the database (%s)" % e.args[1])

			# save the apitoken
			try:
				ATM.insert(token)
			except mdb.DatabaseError, e:
				raise ServerError("Unable to save apitoken in the database (%s)" % e.args[1])

			rdata["apitoken"] = token.getToken()
			rdata["user"] = Depth.build(blank)

			return self._response(rdata, CODE.CREATED)
			try:
				PM.update(victim)	
			except mdb.DatabaseError, e:
				raise ServerError("Unable to update the victim record in the database (%s)" % e.args[1])

			kill.setTime(datetime.now())

			try:
				KM.insert(kill)					
			except mdb.DatabaseError, e:
				raise ServerError("Unable to create the kill record in the db (%s)" % e.args[1])
			
			killer.incrementScore()
			try:
				PM.update(killer)
			except mdb.DatabaseError, e:
				raise ServerError("Unable to update the killer in the database (%s)" % e.args[1])


			return self._response(Depth.build(kill, self.depth), CODE.CREATED)
		else:
			raise BadRequest("Killer and victim_qrcode were not submitted")

	@require_login
	def _doPut(self, dataObject):
		return self._response({}, CODE.UNIMPLEMENTED)

	@require_login
	def _doDelete(self):
		return self._response({}, CODE.UNIMPLEMENTED)
			# handle the possibility the user already exists
			except mdb.IntegrityError, e:
				raise Conflict("A user with that e-mail address exists already.")

			# handle all other DB errors
			except mdb.DatabaseError, e:
				raise ServerError("Unable to create user in the database (%s)" % e.args[1])

			# save the apitoken
			try:
				ATM.insert(token)
			except mdb.DatabaseError, e:
				raise ServerError("Unable to save apitoken in the database (%s)" % e.args[1])

			return self._response(Depth.build(token, self.depth), CODE.CREATED)	
		else:
			raise BadRequest("Required params email and password not sent")

	@require_login
	def _doPut(self, dataObject):

		if "name" in dataObject or "email" in dataObject or "photo" in dataObject:
			try:

				UM = UserMapper()

				if self.arg.isdigit():
					# Get the user by ID
					user = UM.find(self.arg)
				else: