def post(self):
		currentUserprefs = userprefs.get_userprefs()
		current_trip_name = self.request.get('trip_name')
		if len(current_trip_name) == 0:
			current_trip_name = 'Empty trip name'
		trip_key_id = int(self.request.get('trip_key_id', default_value=0))
		if trip_key_id != 0:
			current_trip = trip.get_trip(trip_key_id)
			current_trip.trip_name = current_trip_name
			current_trip.delete_non_creator_members()
		else:
			current_trip = trip.Trip(trip_name = current_trip_name)
		current_trip.put()
		currentUserprefs.current_trip = current_trip
		currentUserprefs.put()
		
		# Update the creator Member data
		creatorMember = member.get_member_for_trip(current_trip.key(), current_trip.created_by_user.email())
		creatorMember.display_name = self.request.get('creator_display_name')
		creatorMember.email_address = member.standardize_email_address(self.request.get('creator_email_address', default_value=''))
		creatorMember.phone_number = member.standardize_phone_number(self.request.get('creator_phone_number'))
		creatorMember.put()
		
		displayNameValues=self.request.get_all('display_name')
		emailAddressValues=self.request.get_all('email_address')
		phoneNumberValues=self.request.get_all('phone_number')
		for i in range(len(displayNameValues)):
			try:
				if len(emailAddressValues[i]) == 0:
					continue
				# Make the key name the email address
				standardized_email_address = member.standardize_email_address(emailAddressValues[i])
				newMember = member.get_member_for_trip(current_trip.key(), standardized_email_address)
				newMember.display_name = displayNameValues[i]
				newMember.email_address = standardized_email_address
				newMember.phone_number = member.standardize_phone_number(phoneNumberValues[i])
				newMember.put();
				# logging.info("Successfully added member.")
				# logging.info("i=" + str(i) + "  displayName = " + displayNameValues[i])
				# logging.info("i=" + str(i) + "  emailAddressValues = " + emailAddressValues[i].lower())
				# logging.info("i=" + str(i) + "  phoneNumberValues = " + phoneNumberValues[i])
			except:
				logging.info("Error: Did not add member at index " + str(i) + ".")
		
		
		# TODO: Clean up the transactions!!!!
		# If an email address got removed then the transactions for the deleted email must go!
		# That is one solution to this problem.
		
		self.redirect('/options')
	def delete_non_creator_members(self):
		# Iterate over all the members using a query.		
		query = db.Query(member.Member)
		query.ancestor(self.key())
		query.filter('email_address !=', member.standardize_email_address(self.created_by_user.email()))
		for aMember in query:
			aMember.delete()
		memcache.delete(str(self.key().id()) + "_allmembers")
def create_default_trip():
	defaultTrip = Trip(trip_name = "Default Solo Trip")
	defaultTrip.put()
	user = users.get_current_user()
	standardized_email_address = member.standardize_email_address(user.email())
	displayName = user.nickname()
	defaultTrip.create_member(standardized_email_address, displayName)
	return defaultTrip
	def is_a_member(self, email_address=None):
		if not email_address:
			email_address = users.get_current_user().email()
		standardized_email_address = member.standardize_email_address(email_address)
		allMembers = self.get_all_members()
		for aMember in allMembers:
			if aMember.email_address == standardized_email_address:
				return True
		return False
def _find_or_create_a_current_trip(userprefs):
	standardized_email_address = member.standardize_email_address(userprefs.user.email())
	query = db.Query(member.Member)
	query.filter("email_address =", standardized_email_address)
	query.order("-created_date_time")
	mostRecentMemberEntityForEmail = query.get()
	if mostRecentMemberEntityForEmail:
		logging.info("Datastore: Found a trip for email address " + standardized_email_address)
		userprefs.current_trip = mostRecentMemberEntityForEmail.key().parent()
	else:
		logging.info("New: Had to create a default trip for email address " + standardized_email_address)
		userprefs.current_trip = trip.create_default_trip()
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		user = users.get_current_user()
		# Set default values for the template data (that will be used if this is a new trip)
		creator_name = user.nickname()
		creator_email = member.standardize_email_address(user.email())
		creator_phone = ""
		trip_name = ""
		trip_key_id = 0
		trip_members = []
		can_delete = False
		# Determine if this is an edit or a new trip
		tripId = self.request.get('id')
		if tripId and int(tripId) != 0: # Shouldn't ever send 0, but just in case my other code glitches :)
			editTrip = trip.get_trip(int(tripId))
			if editTrip.is_a_member():
				# OK you are indeed in the requested trip id, you may edit.  Just checking.
				# Fill in fields with existing data
				trip_name = editTrip.trip_name
				trip_key_id = editTrip.key().id()
				can_delete = editTrip.created_by_user == user
				tripCreatorMember = member.get_member_for_trip(editTrip.key(), member.standardize_email_address(editTrip.created_by_user.email()))
				creator_name = tripCreatorMember.display_name
				creator_email = tripCreatorMember.email_address
				creator_phone = tripCreatorMember.phone_number
				
				
				allMembers = editTrip.get_all_members()
				for aMember in allMembers:
					if aMember.email_address != member.standardize_email_address(editTrip.created_by_user.email()):
						trip_members.append(aMember)
			else:
				self.response.out.write("You do not appear to have access to modify Trip id " + tripId)
				return

		values = {'creator_name': creator_name, 'creator_email': creator_email, 'creator_phone': creator_phone,
				  'trip_name': trip_name, 'trip_key_id': trip_key_id,
				  'trip_members': trip_members,
				  'can_delete': can_delete}
		self.response.out.write(template.render('templates/trip.html', values))
	def create_add_on(self, email_address=None, challenge_type=0, used_add_on=False):
		if not email_address:
			email_address = users.get_current_user().email()
		standardized_email_address = member.standardize_email_address(email_address)
		keyName = standardized_email_address + '_type_' + str(challenge_type)
		newAddOn = transaction.AddOn(key_name=keyName,
				parent = self.key(),
				email_address = standardized_email_address,
				challenge_type = challenge_type,
				used_add_on = used_add_on)
		newAddOn.put()
		logging.info('Memcache: For now delete the _alladdons memcache value (FIX LATER)')
		memcache.delete(str(self.key().id()) + "_alladdons")
		return newAddOn
	def create_member(self, email_address=None, display_name=None, phone_number=''):
		user = users.get_current_user()
		if not email_address:
			email_address = user.email()
		standardized_email_address = member.standardize_email_address(email_address)
		if not display_name:
			display_name = user.nickname()
		newMember = member.Member(key_name=standardized_email_address,
				parent=self.key(),
				email_address=standardized_email_address,
				display_name=display_name,
				phone_number=phone_number)
		newMember.put()
		logging.info('Memcache: For now delete the _allmembers memcache value (FIX LATER)')
		memcache.delete(str(self.key().id()) + "_allmembers")
		return newMember
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		playerResults = {}
		currentTrip = userprefs.get_users_current_trip()
		allTransactions = currentTrip.get_all_transactions()
		for aTransaction in allTransactions:
			if aTransaction.challenge_type == transaction.CHALLENGE_TYPE_INDIVIDUAL_ONLY:
				continue # Skip individual only for this page.
			# Building up a dictionary of playerResults using the email and challenge type as the key in a dictionary
			key = aTransaction.email_address + str(aTransaction.challenge_type)
			if not key in playerResults:
				# This is a new entry in the playerResult dictionary fill in from scratch
				playerResult = {}
				playerResult['total'] = 150
				thisMember = member.get_member_for_trip(currentTrip.key(), aTransaction.email_address);
				playerResult['name'] = thisMember.display_name
				playerResult['email'] = thisMember.email_address
				playerResult['challengeType'] = aTransaction.challenge_type
				playerResult['gamblingEvents'] = []
			else:
				playerResult = playerResults[key]
			
			# Each playerResult has a list of gamblingEvents, add this transaction to the gamblingEvents list
			gamblingEvent = {}
			gamblingEvent['amount'] = aTransaction.amount
			if (aTransaction.amount < 0):
				amountStr = "-$%0.2f" % + abs(aTransaction.amount)
			else:
				amountStr = "+$%0.2f" % aTransaction.amount
			gamblingEvent['amountStr'] = amountStr.replace('.00', '')  # Remove trailing zeros if integer
			gamblingEvent['casino'] = aTransaction.casino
			gamblingEvent['gamePlayed'] = aTransaction.game_played
			gamblingEvent['notes'] = aTransaction.notes
			gamblingEvent['id'] = aTransaction.key().id()
			playerResult['gamblingEvents'].append(gamblingEvent)
			
			playerResult['total'] = playerResult['total'] + aTransaction.amount
			
			playerResults[key] = playerResult
		
		# Okay at this point all of the transactions have been organized into the playerResults dictionary the structure is like this
		# {'[email protected]':
		#    {'total': 165.5,
		#     'name': 'Dave',
		#     'challengeType': 1,
		#     'gamblingEvents': [{'amount': 10.0, 'casino': 'Luxor', 'gamePlayed': 'Blackjack',     'notes': 'blah blah', 'id': 432},
		#                        {'amount':  5.5, 'casino': 'MGM',   'gamePlayed': "Texas Hold'em", 'notes': 'blah blah', 'id': 511}, ... ]},
		#   ... }
		
		# TODO: Change the total and add the usedAddOn boolean
		
		allAddOns = currentTrip.get_all_addons()
		for anAddOn in allAddOns:
			if anAddOn.used_add_on:
				standardized_email_address = member.standardize_email_address(anAddOn.email_address)
				# Find the player key for this Add on
				playerKeyForAddOn = standardized_email_address + str(anAddOn.challenge_type)
				if playerKeyForAddOn in playerResults:
					playerResults[playerKeyForAddOn]['usedAddOn'] = True;
					playerResults[playerKeyForAddOn]['total'] = playerResults[playerKeyForAddOn]['total'] + 50
				
		
		# Next we need to lookup and add the Add-Ons
		#   Change the total and add a field to the dictionary
		# {'[email protected]':
		#    {'total': 215.5,
		#     'name': 'Dave',
		#     'challengeType': 1,
		#     'usedAddOn': True,
		#     'gamblingEvents': [{'amount': 10.0, 'casino': 'Luxor', 'gamePlayed': 'Blackjack',     'notes': 'blah blah', 'id': 432},
		#                        {'amount':  5.5, 'casino': 'MGM',   'gamePlayed': "Texas Hold'em", 'notes': 'blah blah', 'id': 511}, ... ]},
		#   ... }
		
		# Order the keys by their total and create the necessary strings for the renderer
		allKeys = playerResults.keys()
		# sort the keys using the total
		sortedKeys = sorted(allKeys, key=lambda resultKey: -playerResults[resultKey]['total'])
		displayResults = []
		for aKey in sortedKeys:
			displayResult = {}
			if playerResults[aKey]['total'] > 300:
				playerResults[aKey]['total'] = 300
			if playerResults[aKey]['total'] < 0:
				playerResults[aKey]['total'] = 0
			displayResult['challengeId'] = playerResults[aKey]['email'] + '_type_' + str(playerResults[aKey]['challengeType'])
			# Prepare the text that will be displayed at the top level
			challengeText = ''
			if playerResults[aKey]['challengeType'] == transaction.CHALLENGE_TYPE_300_DOLLAR_CHALLENGE:
				challengeText = '$300 Challenge'
			elif playerResults[aKey]['challengeType'] == transaction.CHALLENGE_TYPE_SECOND_CHANCE:
				challengeText = '2nd Chance'
			addOnText = ''
			if 'usedAddOn' in playerResults[aKey] and playerResults[aKey]['usedAddOn']:
				addOnText = '*'
			displayResult['name'] = playerResults[aKey]['name'] + addOnText
			displayResult['challengeType'] = challengeText
			displayResult['total'] = playerResults[aKey]['total']
			totalStr = "$%0.2f" % playerResults[aKey]['total']
			displayResult['totalStr'] = totalStr.replace('.00', '')  # Remove trailing zeros if integer
			displayResult['gamblingEvents'] = playerResults[aKey]['gamblingEvents']
			displayResults.append(displayResult)

		values = {'displayResults': displayResults}
		self.response.out.write(template.render('templates/leaderboard.html', values))
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		currentTrip = userprefs.get_users_current_trip()
		user = users.get_current_user()
		currentMember = member.get_member_for_trip(currentTrip.key(), user.email())
		select_email = member.standardize_email_address(user.email())
		amountValue = ''
		select_challenge_type = 0
		selectCasino = ''
		selectGamePlayed = ''
		transaction_id = 0
		
		# Hardcode some games to practice with the JS
		# These are used by Django
		gamePlayedOptions = ['Blackjack', "Hold'em (no limit)", "Hold'em (limit)","Hold'em (tournament)",
			'Roulette', 'Craps', 'Slots', 'Pai gow poker']
		
		# Hardcode add ons used to practice with the JS
		# These are passed into the JavaScript
		# addOn1 = {'email_address': '*****@*****.**', 'challenge_type': '0'}
		# addOn2 = {'email_address': '*****@*****.**', 'challenge_type': '1'}
		
		addOnsUsed = []
		allAddOns = currentTrip.get_all_addons()
		for anAddOn in allAddOns:
			if anAddOn.used_add_on:
				standardized_email_address = member.standardize_email_address(anAddOn.email_address)
				# Find the player key for this Add on
				addOnsUsed.append({'email_address': standardized_email_address, 'challenge_type': str(anAddOn.challenge_type)})
		
		editingTransactionId = self.request.get('id')
		if editingTransactionId and int(editingTransactionId) != 0: # Shouldn't ever send 0, but just in case my other code glitches :)
			# Get the transaction with this id
			transaction_id = int(editingTransactionId)
			editingTransaction = transaction.get_trip_transaction(currentTrip.key(), transaction_id)
			notes = editingTransaction.notes
			select_email = editingTransaction.email_address
			amountValue = str(editingTransaction.amount)
			select_challenge_type = editingTransaction.challenge_type
			selectCasino = editingTransaction.casino
			selectGamePlayed = editingTransaction.game_played
		else:
			time = datetime.datetime.now()
			now = datetime.datetime.now()
			now += datetime.timedelta(0, 0, 0, 0, 0, -7);  # TODO: Handle daylight savings time issue (-8 standard)
			# for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
			#     print attr, ':', getattr(now, attr)
			# format = "%a %b %d %Y at %H:%M"
			format = "%a"
			dayString = now.strftime(format)
			# notes = 'Created by ' + currentMember.display_name + ' on ' + dateString
			dateString = str(now.month) + "/" + str(now.day) + "/" + str(now.year)
			if now.hour == 0:
				hourStr = '12'
				amPm = 'am'
			elif now.hour < 12:
				hourStr = str(now.hour)
				amPm = 'am'
			elif now.hour == 12:
				hourStr = str(now.hour)
				amPm = 'pm'
			else:
				hourStr = str(now.hour - 12)
				amPm = 'pm'
			timeString =  "%s:%02d %s" % (hourStr, now.minute, amPm)
			notes = 'Created by ' + currentMember.display_name + ' on ' + dayString + ' ' + dateString + ' at ' + timeString
			# DateTime docs at http://docs.python.org/library/datetime.html
		
		
		values = {'transaction_id': transaction_id,
				  'trip_member_options': currentTrip.get_all_members(),
				  'select_email': select_email,
				  'challenge_type_options': transaction.CHALLENGE_TYPES,
				  'select_challenge_type': select_challenge_type,
				  'amount_value': amountValue,
				  'select_casino': selectCasino,
				  'game_played_options': gamePlayedOptions,
				  'all_games': gamePlayedOptions,
				  'select_game_played': selectGamePlayed,
				  'notes': notes,
				  'add_ons_used': addOnsUsed}
		self.response.out.write(template.render('templates/transaction.html', values))