import pygame
import os
import sys
import codecs

import util
from locals import *

class Highscores:
    bg = None
    def __init__(self, screen, new_score = -1):
        self.screen = screen

        self.title = util.bigfont.render("Ennätykset", True, COLOR1)

        if not Highscores.bg:
            Highscores.bg = pygame.image.load("menu/zombie-bg.jpg")

        self.inputting = False
        self.input_score = -1

        self.scores = []
        self.done = False

        self.pathname = util.get_config_path()
        self.filename = self.pathname + "/scores"

        if not os.path.exists(self.filename):
            #print "Creating dummy high scores"
            self.dummy_scores()
        else:
            try:
                f = codecs.open(self.filename, "r", "utf_8")
                i = 0
                name, score = "", 0
                for line in f:
                    if i % 2 == 0:
                        name = line.strip()
                    else:
                        try:
                            score = int(line)
                        except:
                            print "Corrupt high score file."
                            self.dummy_scores()
                            break
                        self.scores.append((name, score))
                    i += 1
            except:
                self.dummy_scores()
                print "Can't open file " + self.filename + " or file corrupt"

        if len(self.scores) < 10:
            print "Corrupt high score file."
            self.dummy_scores()

        if new_score > self.scores[9][1]:
            #print "It's a new high score!"
            #self.inputting = True
            for i in xrange(10):
                if self.scores[i][1] < new_score:
                    self.input_score = i
                    for j in xrange(9 - i):
                        self.scores[9 - j] = self.scores[8 - j]
                    self.scores[i] = [Variables.name, new_score]
                    break

            self.write_scores()

    def run(self):
        while not self.done:
            self.screen.blit(Highscores.bg, self.screen.get_rect())

            rect = self.title.get_rect()
            rect.centerx = MENUCENTER
            rect.top = MENUTOP

            #self.screen.blit(self.title, rect)

            for i in xrange(10):
                color = COLOR1
                #if self.inputting and self.input_score == i:
                if self.input_score == i:
                    color = COLOR2
                score = self.scores[i]
                image = 0
                try:
                    image = util.smallfont.render(str(i + 1) + ". " + score[0], True, color)
                except:
                    image = util.smallfont.render(str(i + 1) + ". Error", True, color)
                rect = image.get_rect()
                rect.top = MENUTOP + 50 + i * 1.2 * rect.height
                rect.left = MENUCENTER - SCREENWIDTH*1/5 + 30
                self.screen.blit(image, rect)

                image = util.smallfont.render(str(score[1]), True, color)
                rect = image.get_rect()
                rect.top = MENUTOP + 50 + i * 1.2 * rect.height
                rect.right = MENUCENTER + SCREENWIDTH*1/5 - 30
                self.screen.blit(image, rect)

            pygame.display.flip()

            nextframe = False
            while not nextframe:
                pygame.event.post(pygame.event.wait())
                for event in pygame.event.get():
                    if event.type == NEXTFRAME:
                        nextframe = True
                        continue
                    if self.inputting:
                        if event.type == QUIT:
                            self.inputting = False
                            self.write_scores()
                        if event.type == KEYDOWN:
                            if event.key == K_RETURN or event.key == K_ESCAPE:
                                self.inputting = False
                                if self.endless:
                                    self.submit_score()
                                self.write_scores()
                            elif event.key == K_BACKSPACE:
                                if len(self.scores[self.input_score][0]) != 0:
                                    self.scores[self.input_score][0] = self.scores[self.input_score][0][:-1]
                            elif event.key == K_SPACE or event.unicode != " ":
                                if len(self.scores[self.input_score][0]) < 32:
                                    self.scores[self.input_score][0] += event.unicode
                    else:
                        if event.type == KEYDOWN or event.type == QUIT or event.type == JOYBUTTONDOWN:
                            self.done = True
                            nextframe = True

    def dummy_scores(self):
        self.scores = []
        self.scores.append(("Zombie",         2000)) # 1
        self.scores.append(("Hectigo",        1500)) # 2
        self.scores.append(("Pekuja",         1250)) # 3
        self.scores.append(("Grilli",         1000)) # 4
        self.scores.append(("Torni",           800)) # 5
        self.scores.append(("Pistooli",        600)) # 6
        self.scores.append(("Biovaarakapseli", 500)) # 7
        self.scores.append(("Veikko",          400)) # 8
        self.scores.append(("Pesismaila",      300)) # 9
        self.scores.append(("Makkara",         200)) #10

        self.write_scores()

    def write_scores(self):
        try:
            f = codecs.open(self.filename, "w", "utf_8")
            for i in xrange(10):
                print >> f, self.scores[i][0]
                print >> f, self.scores[i][1]
        except:
            print "Failed to write high scores to file " + self.filename
            self.done = True
            return
