# Följande kod skrevs under lektionen och är inte ideal med avseende
# på kommentering etc

from collision_checker import *
from tkinter import *
from threading import *
import random
import time

SLEEP = 0.02 # 20 ms
RADIUS = 25
MAX_SPEED = 12

class Ball (Thread):
    def __init__ (self, collisionChecker, canvas):
        self.collisionChecker = collisionChecker
        self.canvas = canvas
        cWidth = int (canvas.cget ('width'))
        cHeight = int (canvas.cget ('height'))
        self.radius = RADIUS
        self.x = random.randrange (self.radius, cWidth - self.radius)
        self.y = random.randrange (self.radius, cHeight - self.radius)
        self.switchDirection ()
        self.collisionChecker.add (self)
        super (Ball, self).__init__ ()

    def birth (self):
        self.id = self.canvas.create_oval (self.x - self.radius,
                                           self.y - self.radius,
                                           self.x + self.radius,
                                           self.y + self.radius,
                                           fill = 'red')
        self.start ()

    def run (self):
        self.running = True
        while self.running:
            if self.collisionChecker.hasCollided (self):
                self.x -= self.dx
                self.y -= self.dy
                self.switchDirection ()
                
            self.canvas.coords (self.id,
                                self.x - self.radius,
                                self.y - self.radius,
                                self.x + self.radius,
                                self.y + self.radius)
            time.sleep (SLEEP)
            self.x += self.dx
            self.y += self.dy

    def switchDirection (self):
        self.dx = random.randint (-MAX_SPEED, MAX_SPEED)
        self.dy = random.randint (-MAX_SPEED, MAX_SPEED)

    def shutDown (self):
        self.running = False
        self.join ()
