import pygame
import psycopg2
import collections
from buttons import Buttons
from quit import process_events
from itertools import chain


blue = (30, 15, 170) #RGB numbers for various needed colours
yellow = (255, 255, 0)
white = (255, 255, 255)


def data_shredder(a): #removes the tuple and the list
    res = ''
    if isinstance(a, collections.Iterable):
        for item in a:
            res +=  str(data_shredder(item)) + ' '
    else:
        res = str(a)
    return res

def interact_with_database(command):
    # Connect and set up cursor
    connection = psycopg2.connect("dbname=project2db user=postgres password=root")
    cursor = connection.cursor()

    # Execute the command
    cursor.execute(command)
    connection.commit()

    # Save results
    results = None
    try:
        results = cursor.fetchall()
    except psycopg2.ProgrammingError:
        # Nothing to fetch
        pass

    # Close connection
    cursor.close()
    connection.close()

    return results

def download_names(): #get the items from the database
    return interact_with_database("SELECT name FROM score Order By wins DESC")
def download_wins():
    return interact_with_database("SELECT wins FROM score Order By wins DESC")
def download_losses():
    return interact_with_database("SELECT losses FROM score Order By wins DESC")
def download_ratio():
    interact_with_database("SELECT score FROM score")

def update_wins(name, wins): #not used atm
    interact_with_database("UPDATE score SET wins = {} WHERE name = '{}' ".format(wins, name))

def update_losses(name, losses):
    interact_with_database("UPDATE score SET losses = {} WHERE name = '{}' ")

def amount(): #gets the number of items in the table
    tuple_list = interact_with_database("SELECT count(name) FROM score")
    return data_shredder(tuple_list) #removes the tuple and the list

def ratio(id):
    losses = interact_with_database("SELECT losses FROM score WHERE name = {}".format(id))
    wins = interact_with_database("SELECT wins FROM score WHERE name = {}".format(id))
    losses = int(data_shredder(losses))
    wins = int(data_shredder(wins))
    total = wins + losses
    ratio = losses / total
    score = (1 - ratio) * 100
    update_score(id, score)


def highscore():
    pygame.init() 

    dispinfo = pygame.display.Info()
    size = (dispinfo.current_w, dispinfo.current_h)
    width = dispinfo.current_w #Size for the screen in pixels
    height = dispinfo.current_h


    screen = pygame.display.set_mode(size, pygame.FULLSCREEN) #Make a window with the size stated above


    bg = pygame.image.load("black.jpg") #Load in a background
    bg = pygame.transform.scale(bg,(width,height))

    leave = Buttons(width, height, 0.8, 0.9, "Return")

    name = Buttons(width, height, 0.000000001, 0.9, "Highscore")

    myfont = pygame.font.SysFont(None, 30)

    playerName = list(download_names())
    playerWins = list(download_wins()) #store the list from the database
    playerLosses = list(download_losses())
    screen.blit(bg, (0, 0))#Draw the background
    y = 50
    l = myfont.render("Highscore",1,(255,255,0)) #display each item on the screen
    screen.blit(l, (750,y))

    a = 0
    a = len(playerName)

    if a > 10:
        a = 10

    for i in range(a):
        tempplayername = playerName[i][0]
        tempplayerwins = playerWins[i][0]
        tempplayerlosses = playerLosses[i][0]

        playerName.append(tempplayername)
        playerWins.append(tempplayerwins)
        playerLosses.append(tempplayerlosses)


        y += 25
        l = myfont.render("{}   Name:     {}".format(i+1, playerName[i]),1,(255,255,0)) #display each item on the screen
        screen.blit(l, (750,y))
        y += 25
        l = myfont.render("     Wins:     {}".format(playerWins[i]),1,(255,255,0)) #display each item on the screen
        screen.blit(l, (750,y))
        y += 25
        l = myfont.render("     Losses:   {}".format(playerLosses[i]),1,(255,255,0)) #display each item on the screen
        screen.blit(l, (750,y))
        y += 25

         #change the pos of the next textbox so they dont overlap

    while not process_events(): #Loop to keep refreshing the screen while the window is not closed

        name.draw(screen, 400, 70) #draw the name on the screen
        screen.blit(name.write(100), ((int(name.width * name.xpos), int(name.height * name.ypos))))

        leave.draw(screen, 300, 47) #draw the exit button
        screen.blit(leave.write(65), ((int(leave.width * leave.xpos), int(leave.height * leave.ypos))))

        if pygame.mouse.get_pressed()[0] and leave.clicked():
            from menu import program
            program()

        if leave.clicked():
            leave.tcolor = yellow
            leave.bcolor = blue
        if not leave.clicked():
            leave.bcolor = blue
            leave.tcolor = white

        pygame.display.flip() #Flips the screen so that everything updates