from typing import Self

from . import config



class Score:
	def __init__( self:Self, name:str,points:int ):
		self.name  :str = name
		self.points:int = points



highscores:list[Score] = []

def load():
	global highscores

	highscores = []
	try:
		with open( config.FILEPATH_HIGHSCORES, "r" ) as hs_file:
			data = hs_file.read()

		for line in data.split("\n"):
			line = line.strip()
			if len(line)==0 or line[0]=="#": continue

			name, points = line.split("*")
			points = int(points)
			highscores.append(Score( name, points ))
	except FileNotFoundError:
		#Create if not present
		for points in [
			300000, 250000, 200000, 180000, 160000, 140000, 130000, 120000, 110000, 100000
		]:
			highscores.append(Score( "YOUR NAME HERE", points ))

def save():
	with open( config.FILEPATH_HIGHSCORES, "w" ) as hs_file:
		for score in highscores:
			hs_file.write(f"{score.name}*{score.points}\n")

def is_highscore( points:int ):
	for highscore in highscores:
		if points > highscore.points:
			return True
	return False

def insert_score( score:Score ):
	global highscores

	k = 0
	while k < len(highscores):
		if score.points > highscores[k].points:
			break
		k += 1
	highscores.insert( k, score )

	highscores = highscores[:config.HIGHSCORES_COUNT]
