import pspos
import random

lista_level_set = []
authors = []
n_levels = [] # n. livelli per ogni level set

levels = []
ball_position = []

listFile = pspos.listdir("lvls/")
for file in listFile:
    nome_file = file.split(".")
    if nome_file[1] == 'txt':
        lista_level_set.append(nome_file[0])
        fl = open("lvls/%s.txt" %nome_file[0])
        for line in fl.readlines():
            if line[0] == "#":
                authors.append(line[1:len(line)].split(',')[0])
                n_levels.append(int(line[1:len(line)].split(',')[1]))
                break
    
def initialize(levelSet):
    global levels, ball_position, author
    if levelSet != 'random':
        levels = []
        ball_position = []
        
        fl = open("lvls/%s" %levelSet)

        levels.append([])
        i = 0
        for line in fl.readlines():
            if line[0] != "#":
                if len(line) != 1:
                    levels[i].append(line.replace(" ", ""))
                else:
                    levels.append([])
                    i += 1
        #print levels[1]
        fl.close()

        nLiv = 0
        i = 0 # dispari -> 8 palle; pari -> 7 palle.
        for level in levels:
            ball_position.append([])
            for line in level:
                x = 0
                for lettera in line:
                    x += 1
                    if lettera != "-" and lettera != "\n":
                        if i % 2 == 0:
                            ball_position[nLiv].append((32+(x*21), 25+(18*i), int(lettera)))
                        else:
                            ball_position[nLiv].append((32+(x*21+(7*1.5)), 25+(18*i), int(lettera)))
                i += 1
            i = 0
            nLiv += 1
    else: # initialize random level
        levels = []
        ball_position = []
        
        levels.append([])
        for i in range(10):
            if i <= 4:
                if i % 2 == 0:
                    levels[0].append('%d%d%d%d%d%d%d%d\n'%(random.randint(1,7), random.randint(1,7), random.randint(1,7), random.randint(1,7),\
                                                           random.randint(1,7), random.randint(1,7), random.randint(1,7), random.randint(1,7)))
                else:
                    levels[0].append('%d%d%d%d%d%d%d\n'%(random.randint(1,7), random.randint(1,7), random.randint(1,7), random.randint(1,7),\
                                                         random.randint(1,7), random.randint(1,7), random.randint(1,7)))
            else:
                if i % 2 == 0:
                    levels[0].append('--------\n')
                else:
                    levels[0].append('-------\n')
                
        nLiv = 0
        i = 0 # dispari -> 8 palle; pari -> 7 palle.
        for level in levels:
            ball_position.append([])
            for line in level:
                x = 0
                for lettera in line:
                    x += 1
                    if lettera != "-" and lettera != "\n":
                        if i % 2 == 0:
                            ball_position[nLiv].append((32+(x*21), 25+(18*i), int(lettera)))
                        else:
                            ball_position[nLiv].append((32+(x*21+(7*1.5)), 25+(18*i), int(lettera)))
                i += 1
            i = 0
            nLiv += 1

def getHighScore(levelset, lvl):
    ## lv,temposec;lv,temposec
    fl = open("lvls/%s.rec" %levelset, "r")
    buf = fl.read()
    fl.close()
    lista = buf.split(";")
    tempi = ''
    if buf != '':
        for l in lista:
            if int(l.split(",")[0]) == lvl:
                tempi = l.split(",")[1]
                break
        if tempi != '':
            return int(tempi) # sec
        else:
            return None # Non esiste un record sul livello lvl
    else:
        return None

def setHighScore(levelSet, lvl, time): 
    fl = open("lvls/%s.rec" %levelSet, "r")
    buf = fl.read()
    fl.close()
    list = []
        
    if buf != '':
        for i in buf.split(";"):
            list.append([int(i.split(",")[0]), int(i.split(",")[1])])
        theres = False
        where = 0
        for i in list:
            if i[0] == lvl:
                theres = True
                break
            where += 1
        if theres:
            list[where][1] = time
        else:
            list.append([lvl, time])
    else:
        list.append([lvl, time])

    for i in range(len(list)):
        for j in (0, 1):
            list[i][j] = str(list[i][j])

    buf = ''
    for i in list:
        buf += ",".join(i) + ";"

    fl = open("lvls/%s.rec" %levelSet, "w")
    print >> fl, buf[0:len(buf)-1]
    fl.close()
