from tkinter import *
import color

# Var
ACCENT_COLOR = color.PURPLE
SECONDARY_COLOR = color.BROWN
canvas = None

# Touches
haut = False
bas = False

# Trait
trait = None
T_WIDTH = 10
T_HEIGHT = 90
PAST_Y = 5

# Balle
balle = None
cos = 0.0
sin = 0.0
B_RADIUS = 10
PASB = 3.0

image = None

# Main
def main(c: Canvas):
    global canvas, trait, balle, cos, sin, image
    canvas = c
    image = PhotoImage(file ="res/Barre.png")

    x_t = 360
    y_t = 150
    x_b = 200
    y_b = 150
    trait = canvas.create_image(x_t, y_t, image = image)
    balle = canvas.create_oval(x_b - B_RADIUS, y_b - B_RADIUS, x_b + B_RADIUS, y_b + B_RADIUS, outline = SECONDARY_COLOR, fill = SECONDARY_COLOR)

    cos = -0.5
    sin = 0.8660

    win = canvas.master
    win.bind('<z>', lambda event: haut_event(True))
    win.bind('<s>', lambda event: bas_event(True))
    win.bind('<KeyRelease-z>', lambda event: haut_event(False))
    win.bind('<KeyRelease-s>', lambda event: bas_event(False))

# Loop
def loop(deltatime: float, difficulty: float, end):
    collision()
    deplacementballe(difficulty)
    deplacementtrait(difficulty)

    _, _, x2, _ = canvas.coords(balle)
    if x2 >= 396:
        end()
        return

# DĂ©placement de la balle
def deplacementballe(difficulty: float):
    canvas.move(balle, cos * PASB * difficulty, -sin * PASB * difficulty)

def collision():
    global cos, sin

    xt1, yt1 = canvas.coords(trait)
    xt1, yt1, xt2, yt2 = xt1 - 5, yt1 - 45, xt1 + 5, yt1 + 45
    x1, y1, x2, y2 = canvas.coords(balle)
    if x1 <= 5:
        cos = -cos
    if y1 <= 5 or y2 >= 295:
        sin = -sin
    if x2 + 5 >= xt1 and x1 - 5 <= xt2 and y1 - 5 <= yt2 and y2 + 5 >= yt1:
        cos = -abs(cos)
        canvas.itemconfigure(balle, outline = ACCENT_COLOR, fill = ACCENT_COLOR)
        canvas.after(200, lambda: canvas.itemconfigure(balle, outline=SECONDARY_COLOR, fill=SECONDARY_COLOR))

def deplacementtrait(difficulty: float):
    _, y1 = canvas.coords(trait)
    y1, y2 = y1 - 45, y1 + 45
    if haut and y1 >= 10:
        canvas.move(trait, 0, -PAST_Y * difficulty)
    if bas and y2 <= 290:
        canvas.move(trait, 0, PAST_Y * difficulty)

def haut_event(pressed: bool):
    global haut
    haut = pressed

def bas_event(pressed: bool):
    global bas
    bas = pressed

