
import datetime


class Scoring:
    # ==================== SCORING ====================
    
    def save_score(self):
        # Save to traditional scores.txt file
        with open("scores.txt", "a") as f:
            player_name = getattr(self, 'profile_integration', None)
            if player_name and hasattr(player_name, 'get_profile_name'):
                name = player_name.get_profile_name()
                device_id = player_name.get_device_id()
                f.write(f"{datetime.datetime.now()} - {self.points} - {name} - {device_id}\n")
            else:
                f.write(f"{datetime.datetime.now()} - {self.points} - Guest\n")
    
    def read_score(self):
        table = []
        try:
            with open("scores.txt") as f:
                rows = f.read().splitlines()
                for row in rows:
                    parts = row.split(" - ")
                    if len(parts) >= 2:
                        # Handle both old format (date - score) and new format (date - score - name - device)
                        if len(parts) >= 4:
                            table.append([parts[0], parts[1], parts[2], parts[3]])  # date, score, name, device
                        elif len(parts) >= 3:
                            table.append([parts[0], parts[1], parts[2], "Unknown"])  # date, score, name, unknown device
                        else:
                            table.append([parts[0], parts[1], "Guest", "Unknown"])  # date, score, guest, unknown device
                table.sort(key=lambda x: int(x[1]), reverse=True) 
        except FileNotFoundError:
            pass
        return table[:5]  # Return top 5 scores instead of 3
        
    def add_point(self, value):
        self.points += value