from uib_inf100_graphics.event_app import run_app
from ball import draw_ball_in_box
import random

def app_started(app):
    app.player = {
        'x': app.width/2,
        'y': app.height - 50,
        'radius': 30
    }
    app.pressed_keys = []
    app.timer_delay = 1000//60 # 1000 millisekunder / 60 bilder

    app.apples = [{
        'x' : app.width/2,
        'y' : 0,
        'radius' : 20
    },
    {
        'x' : app.width/3,
        'y' : 0,
        'radius' : 15
    }]
    app.score = 0
    app.state = 'active'
    app.apple_count = 2
    app.max = 50

def key_pressed(app, event):
    # legg til event.key i listen over nedtrykkede knapper.
    if event.key == 'Left':
        app.pressed_keys.append('Left')
    if event.key == 'Right':
        app.pressed_keys.append('Right')   

def key_released(app, event):
    # fjern event.key fra listen.
    if event.key == 'Left':
        app.pressed_keys.remove('Left')
    if event.key == 'Right':
        app.pressed_keys.remove('Right')  

def timer_fired(app):
    # hvis 'Left' ('Right') nedtrykket, flytt 10 til venstre (høyre).
    if 'Left' in app.pressed_keys:
        app.player['x'] -= 10
    elif 'Right' in app.pressed_keys:
        app.player['x'] += 10

    # flytt eplene nedover (økt y-verdi).
    for apple in app.apples:
        apple['y'] += 5

    # timer_fired: for hvert eple, 
    # sjekk om det krasjer med player (husk fra lab2: circles overlap). 
    # Øk score hvis treff. 
    # Ta vare på eplet hvis bom.
    remaining_apples = []
    for apple in app.apples:
        if circles_overlap(app.player['x'], app.player['y'], app.player['radius'],
                           apple['x'], apple['y'], apple['radius']):
            app.score += 1
        else:
            remaining_apples.append(apple)
    app.apples = remaining_apples

    # med 10% sannsynlighet, 
    # opprett et eple med tilfeldig x-verdi og tilfeldig radius
    a_random_value = random.random()
    threshold = 0.1
    if a_random_value < threshold and app.apple_count < app.max:
        new_apple = {
            'x' : random.randrange(app.width),
            'y' : 0,
            'radius' : random.randrange(20, 50)
        }
        app.apples.append(new_apple)
        app.apple_count += 1

    # Fjern epler fra listen av epler hvis det faller nedenfor skjermbildet
    remaining_apples = []
    for apple in app.apples:
        if apple['y'] - apple['radius'] >= app.height:
            ...
        else:
            remaining_apples.append(apple)
    app.apples = remaining_apples

    # Når maks antall epler er opprettet, 
    # OG det ikke er flere epler igjen: sett game_state til ‘game_over’
    if app.apple_count == app.max and len(app.apples) == 0:
        app.state = 'game_over'
        

def distance(x1, y1, x2, y2):
    return ((x1-x2)**2 + (y1-y2)**2)**0.5

def circles_overlap(x1, y1, r1, x2, y2, r2):
    if distance(x1, y1, x2, y2) <= r1 + r2:
        return True
    else:
        return False

def redraw_all_active(app, canvas):
    # tegn spilleren
    x_left = app.player['x'] - app.player['radius']
    y_top = app.player['y'] - app.player['radius']
    x_right = app.player['x'] + app.player['radius']
    y_bottom = app.player['y'] + app.player['radius']
    color = 'yellow'
    draw_ball_in_box(canvas, x_left, y_top, x_right, y_bottom, color)

    # tegn eplene
    for apple in app.apples:
        x_left = apple['x'] - apple['radius']
        y_top = apple['y'] - apple['radius']
        x_right = apple['x'] + apple['radius']
        y_bottom = apple['y'] + apple['radius']
        color = 'red'
        canvas.create_oval(x_left, y_top, x_right, y_bottom, fill=color)

    canvas.create_text(app.width/2, 50, text=f'{app.score}', font='Arial 40')

def redraw_all_game_over(app, canvas):
    canvas.create_text(app.width/2, app.height/2, 
                       text=f'Game Over\n Your score is {app.score}/{app.max} points',
                       font='Arial 40')

def redraw_all(app, canvas):
    if app.state == 'active':
        redraw_all_active(app, canvas)
    elif app.state == 'game_over':
        redraw_all_game_over(app, canvas)

run_app(width=600, height=800, title='eplesamler')