from tkinter import *
from random import randint
import color

# Variables
canvas = None
ACCENT_COLOR = color.PINK
SECONDARY_COLOR = color.BROWN

# Touche
space_press = False
space_release = True

# Decompte
decompte = None
texte = None
valeur = None
D_WIDHT = 10
d_height = 0
D_PAS = 1


# Main
def main(c: Canvas):
    global canvas, D_WIDHT, decompte
    canvas = c

    win = canvas.master
    win.bind('<space>', lambda event: space_press_event(event))
    win.bind('<KeyRelease-space>', lambda event: space_release_event(event))

    decompte = canvas.create_line(395, d_height, 395, 300, width = D_WIDHT, fill = ACCENT_COLOR)
    create_text()

# Loop
def loop(deltatime: float, difficulty: float, end):
    global space_press, space_release, texte, decompte

    # Bouger barre
    canvas.move(decompte, 0, D_PAS * difficulty)

    # Obtenir coordonnées barre
    _, y1, _, _ = canvas.coords(decompte)

    # verif_touche_espace
    if space_press and space_release:
        diminuer_texte()
        space_release = False
        canvas.itemconfigure(texte, fill = SECONDARY_COLOR)
        canvas.after(100, lambda: canvas.itemconfigure(texte, fill = ACCENT_COLOR))

    # Vérifier condition défaite
    if valeur < 0:
        end()
        return

    if y1 >= 300:
        if valeur != 0:
            end()
            return
        else:
            #remise à zéro
            canvas.delete(decompte, texte)
            decompte = canvas.create_line(395, d_height, 395, 300, width = D_WIDHT, fill = ACCENT_COLOR)
            create_text()

def create_text():
    global texte, valeur

    valeur = randint(1, 6)
    texte = canvas.create_text(200, 150, text = valeur, fill = ACCENT_COLOR, font = (None, 58))

def diminuer_texte():
    global valeur

    valeur -= 1

    # Empêcher affichage -1
    if valeur < 0:
        canvas.itemconfigure(texte, text = "Perdu !")
        return

    canvas.itemconfigure(texte, text = valeur)

def space_press_event(event):
    global space_press

    space_press = True

def space_release_event(event):
    global space_release, space_press

    space_press = False
    space_release = True
