# Highscores class - looks after file IO and updating them
#
# Highscores are stored on per line basis. First Player, then score.. and so on
# only the top 10 are displayed, rest is ignored but saved

import pygame
import globals
import math

class HighScores:
	
	def __init__(self, fnt):
		f = open(globals.String_HighScores, 'r')
		self.data = f.readlines()
		f.close
		
		self.font = fnt
		
	def AddScore(self, score):
		strscore = str(score)
		count = 1
		done = 0
		
		while(done == 0 and count < len(self.data)):
			if(score > int(self.data[count])): 
				done = 1
			count += 2
		
		count -= 3
		if(count < 20):
			name = self.GetPlayerName()
#			print(name, strscore)
			self.data.insert(count, strscore+'\n')
			self.data.insert(count, name+'\n')
			
		self.DrawScores()
		return count
	
	def DrawScores(self):
		globals.screen.fill(globals.bkblue, [430, 430, 140, 306])
		count = len(self.data)
		if count > 16: count = 16
		flip = 0
			
		for i in range(0, count):
			img = self.font.render(self.data[i], 1, globals.white);
			posx = 430
			if(flip == 1): posx = 570 - self.font.size(self.data[i])[0]
			globals.screen.blit(img, [posx, 430 + (i/2) * 38])
			flip = 1-flip
		
	def GetPlayerName(self):
		done = 0
		name = ""
		letters = 3
		
		savescreen = pygame.Surface([600, 760])
		savescreen.blit(globals.screen, [0,0])
		
		globals.screen.fill(globals.black, [50, 200, 300, 150])
		img = self.font.render("New high score", 1, globals.white, globals.black);
		globals.screen.blit(img, [80, 220])
		img = self.font.render("Enter name:", 1, globals.white, globals.black);
		globals.screen.blit(img, [80, 260])
		
		pos = [150, 300]
		
		while(letters > 0):
						
			for event in pygame.event.get():
				if event.type == pygame.KEYUP:
					if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN:
						globals.screen.blit(savescreen, [0,0])
						return name
					else:
						key = pygame.key.name(event.key)
						if(key >= 'a' and key <= 'z' and len(key) == 1):
							name += key
							img = self.font.render(str(key), 1, globals.white, globals.black);
							globals.screen.blit(img, pos)
							pos = [pos[0] + 24, pos[1]]
							
							letters -= 1
			
			pygame.display.flip()
			pygame.time.wait(20)
		
		pygame.time.wait(1000)
		globals.screen.blit(savescreen, [0,0])
		return name
	
	def SaveScores(self):
#		print("Saving....")
		f = open(globals.String_HighScores, 'w')	
		for d in self.data:
			f.write(d)
		f.close()

