#!/usr/bin/python
# -*- coding:utf-8 -*-

##### class interne #####
class Score(object):
    # attributs a ajouter : niveau atteint, date, ...
    def __init__(self, points = 0, pseudo = "inconnu"):
        self.points = points
        self.pseudo = pseudo
    def __str__(self):
        return '%i %s' % (int(self.points), self.pseudo)
    def __eq__(self, other):
        return self.points == other.points
    def __gt__(self, other):
        return self.points > other.points
    def __ge__(self, other):
        return self.points >= other.points

##### class externe #####
class Scores_List(object):
    # attributs a ajouter : nb de scores max
    def __init__(self, file_name):
        self.file_name = file_name
        scores_file = open (file_name, 'r', 1)
        self.list = []
        for line in scores_file:
            self.list.append(parse_line(line))
        scores_file.close()

    def winner(self, points):
        return points > self.list[-1].points
    
    def add(self, points, pseudo):
        new_score = Score(points, pseudo)
        scores_nb = len(self.list)
        new_score_rank = 0
        while new_score_rank < scores_nb and self.list[new_score_rank] >= new_score:
            new_score_rank += 1
        if new_score_rank < scores_nb:
            # on est dans les meilleurs scores
            self.list.insert(new_score_rank, new_score)
            self.list.pop()

    def consult(self):
        return [str(score) for score in self.list]

    def register(self):
        scores_file = open (self.file_name, 'w', 1)
        for score in self.list:
            scores_file.write(str(score)+'\n')
        scores_file.close()        
                
##### fonction interne #####        
def parse_line(line):
    sep = line.find(' ')
    # before space
    points = line[:sep]
    # after space, without final '\n'
    pseudo = line[sep+1:-1]
    resultat = Score(int(points), pseudo)
    return resultat

######### programme de test #########
# conseil : lancer make test_scores #
#####################################
if __name__ == "__main__":
    SCORES_FILE_NAME = ".scores"
    monoplayermode_scores = Scores_List(SCORES_FILE_NAME)
    for points, pseudo in [(123,"popol"), (22,"coquelicot"), (201,"the_boss"), (0,"raton")]:
        if monoplayermode_scores.winner(points):
            monoplayermode_scores.add(points, pseudo)
    for string in monoplayermode_scores.consult():
        print string
    monoplayermode_scores.register()
