"""File for Category class.""" import json from data.score import Score, ScoreTime # pylint: disable=import-error class Category: """Stores a category's information and relative scores.""" def __init__(self, name: str, ascending: bool, time_record: bool, score_map: dict) -> None: self._name: str = name self._ascending: bool = ascending self._time_record: bool = time_record self._scores_map: dict = score_map def __str__(self) -> str: """Creates a string from the class.""" return json.dumps(self.to_dict(), indent=4) @classmethod def from_dict(cls, name: str, data: dict): """Fills out category from passed dictionary""" ascending = data["ascending"] time_record = data["time_record"] score_map = {} for user, score in data["scores"].items(): if time_record: score_map[user] = ScoreTime(user, score) else: score_map[user] = Score(user, score) return cls(name, ascending, time_record, score_map) @property def ascending(self) -> bool: """Getter for ascending bool.""" return self._ascending @property def name(self) -> str: """Getter for name.""" return self._name @property def time_record(self) -> bool: """Getter for time record bool.""" return self._time_record @property def scores(self) -> "list[Score]": """Getter for scores list.""" return self._scores_map.values() def add_score(self, score: Score) -> None: """Adds a score to dictionary storage. Then sorts dictionary by score value.""" if score.user in self._scores_map: self._scores_map[score.user].value = score.value else: self._scores_map[score.user] = score self._scores_map = dict( sorted(self._scores_map.items(), key=lambda x: x[1].score, reverse=not self.ascending) ) def get_user_score(self, user: str) -> Score: """Gets a user's score. None if doesn't exist.""" if user in self.scores: return self._scores_map[user] return None def remove_score(self, score: Score) -> None: """Removes a score from dictionary storage.""" score = self._scores_map.pop(score.user) del score def to_dict(self) -> dict: """Saves category data as a python dictionary.""" data = {} data["ascending"] = self.ascending data["time_record"] = self.time_record data["scores"] = {} for score in self.scores: data["scores"][score.user] = score.value return data