#! /usr/bin/python

import requests, pprint, json
from collections import defaultdict

class GuardianStats:
	# Bungie API KEY
	
api_key       = '1b6d2823d9ba455db6d22c0c75ae55a2'

	def __init__(self, psn_id):
		self.membership_id = self.GetMembershipID(psn_id)
		self.character_id  = self.GetLatestUsedGuardian(self.membership_id)

	def GetMembershipID(self, psn_id):
		membership_id = None
		api_endpoint  = 'https://www.bungie.net/Platform/Destiny/SearchDestinyPlayer/2/'+psn_id
		headers       = {'X-API-Key': self.api_key}
		r             = requests.get(api_endpoint, headers=headers)
		if r.status_code == 200 :
			data          = r.json()
			membership_id = data['Response'][0]['membershipId']
		else:
			print 'HTTP error: '+r.status_code
		return membership_id
	
	def GetLatestUsedGuardian(self, membership_id):
		last_guardian_id = None
		api_endpoint     = 'https://www.bungie.net/Platform/Destiny/2/Account/'+membership_id+'/Summary/'
		headers          = {'X-API-Key': self.api_key}
		r                = requests.get(api_endpoint, headers=headers)
		if r.status_code == 200 :
			data          = r.json()
			characters    = data['Response']['data']['characters']
			data          = defaultdict(dict)
			for character in characters :
				character_id      = character['characterBase']['characterId']
				last_played       = character['characterBase']['dateLastPlayed']
				data[last_played] = character_id
			dates            = sorted(data.keys(), reverse=True)
			last_guardian_id = data[dates[0]]
		else:
			print 'HTTP error: '+r.status_code
		return last_guardian_id

	def GetPlayerStats_V2(self, membership_id, mode_id):
		stats         = None
		api_endpoint  = 'http://api.guardian.gg/v2/players/'+membership_id
		r             = requests.get(api_endpoint)
		if r.status_code == 200 :
			data  = r.json()
			stats = data['data']['modes'][str(mode_id)]
		else:
			print 'HTTP error: '+r.status_code
		return stats
	
	# OLD METHOD (is the only method with rank still checking how to loop and get it)
	def GetPlayerStats(self, mode_id):
		stats         = None
		membership_id = self.membership_id
		api_endpoint  = 'http://api.guardian.gg/elo/'+membership_id
		print api_endpoint
		r             = requests.get(api_endpoint)
		if r.status_code == 200 :
			data  = r.json()
			# stats = data['data']['modes'][mode_id]
		else:
			print 'HTTP error: '+r.status_code
		return stats
	
	def GetActivityID(self, mode_id):
		activity_id   = None
		membership_id = self.membership_id
		character_id  = self.character_id
		api_endpoint  = 'https://www.bungie.net/Platform/Destiny/Stats/ActivityHistory/2/'+membership_id+'/'+character_id+'/?mode='+mode_id+'&count=1&lc=en'
		headers       = {'X-API-Key': self.api_key}
		r             = requests.get(api_endpoint, headers=headers)
		if r.status_code == 200 :
			data        = r.json()
			activity_id = data['Response']['data']['activities'][0]['activityDetails']['instanceId']
		else:
			print 'HTTP error: '+r.status_code
		return activity_id
	
	def GetPostCarnageReport(self, mode_id):
		report        = None
		activity_id   = self.GetActivityID(str(mode_id))
		api_endpoint  = 'https://www.bungie.net/Platform/Destiny/Stats/PostGameCarnageReport/'+activity_id+'/?lc=en'
		headers       = {'X-API-Key': self.api_key}
		r             = requests.get(api_endpoint, headers=headers)
		if r.status_code == 200 :
			data    = r.json()
			report  = defaultdict(dict)
			period  = data['Response']['data']['period']
			players = data['Response']['data']['entries']
			teams   = data['Response']['data']['teams']
			mode_id = data['Response']['data']['activityDetails']['mode']
			# Mapping the teams
			team_map = defaultdict(dict)
			for team in teams :
				# Assigning more friendly variables
				team_id             = int(team['teamId'])
				team_name           = team['teamName']
				team_standing       = team['standing']['basic']['displayValue']
				team_standing_value = int(team['standing']['basic']['value'])
				team_score          = int(team['score']['basic']['value'])
				# Assigning the team map
				team_map[team_id]['standing'] = team_standing
				team_map[team_id]['name']     = team_name
				# Building the report
				report[team_standing_value]['team_score'] = team_score
				report[team_standing_value]['team_name']  = team_name
				report[team_standing_value]['player']     = []
			# Mapping the players
			for guardian in players :
				guardian_standing = int(guardian['standing'])
				display_name      = guardian['player']['destinyUserInfo']['displayName']
				membership_id     = guardian['player']['destinyUserInfo']['membershipId']
				stats             = self.GetPlayerStats_V2(membership_id, mode_id)
				elo               = int(stats['elo'])
				player_data = {
					'display_name'  : display_name,
					'membership_id' : membership_id,
					'kills'         : int(guardian['values']['kills']['basic']['value']),
					'deaths'        : int(guardian['values']['deaths']['basic']['value']),
					'team'          : guardian['values']['team']['basic']['displayValue'],
					'team_id'       : int(guardian['values']['team']['basic']['value']),
					'team_standing' : team_map[guardian['values']['team']['basic']['value']]['standing'],
					'elo'           : elo
				}
				report[guardian_standing]['player'].append(player_data)
		else:
			print 'HTTP error: '+r.status_code
		return report