import os.path
from functions import getConfigDir

class HiScores:    
	def __init__(self):
		self.file = None
		self.scores = [[0,0,0] for i in range(10)]
		if (os.path.exists(os.path.join(getConfigDir(),"hiscores"))):
			self.load()
		else:
			self.loadStart("hiscores")
		self.save()
		
	def checkAndSave(self,score):
		scorel = list(score)
		li = self.getLastScoreIndex()
		ls = self.getLastScore()
		if (li<9):
			self.scores[9] = scorel
		else:
			if (score[0]>self.scores[9][0]):
				self.scores[9] = scorel
			elif (score[0]==self.scores[9][0] and ((score[1]>self.scores[9][1]) or (score[2]>self.scores[9][2]))):
				self.scores[9] = scorel
		self.scores.sort(reverse=True)
		self.save()
		
	def getLastScoreIndex(self):
		wyn = 0
		for i in range(10):
			if (len(self.scores[i])>2):
				wyn = i
		return wyn
	
	def getLastScore(self):
		return self.scores[self.getLastScoreIndex()]
		
	def load(self):
		self.file = os.path.join(getConfigDir(),"hiscores")
		plik = open(self.file)
		zaw = plik.readlines()
		i = 0
		for elem in zaw:
			if (len(elem)>2):
				tmp = elem.split(".")
				self.scores[i][0] = int(tmp[0])
				self.scores[i][1] = int(tmp[1])
				self.scores[i][2] = int(tmp[2])
				i+=1
		plik.close()
		
	def loadStart(self,filename):
		self.file = os.path.join(getConfigDir(),filename)
		plik = open(filename)
		zaw = plik.readlines()
		i = 0
		for elem in zaw:
			if (len(elem)>2):
				tmp = elem.split(".")
				self.scores[i][0] = int(tmp[0])
				self.scores[i][1] = int(tmp[1])
				self.scores[i][2] = int(tmp[2])
				i+=1
		plik.close()
		
	def save(self):
		plik = open(self.file,"w")
		for i in range(len(self.scores)):
			elem = self.scores[i]
			if (len(elem)>2):
				tmp = str(elem[0])+"."+str(elem[1])+"."+str(elem[2])+"\n"
				plik.write(tmp)
		plik.close()
		