__author__ = 'catears'
# Henrik 'catears' Adolfsson
# henad221@student.liu.se

"""
Example context with balls that move randomly
"""

import random

from context import EmptyContext


def outside_l(circle):
    return circle['pos'][0] - circle['r'] <= 0


def outside_r(circle):
    return circle['pos'][0] + circle['r'] >= g.width


def outside_u(circle):
    return circle['pos'][1] - circle['r'] <= 0


def outside_d(circle):
    return circle['pos'][1] + circle['r'] >= g.height


def update_movement(circle):
    if outside_l(circle) and circle['movement'][0] < 0:
        circle['movement'][0] *= -1
    elif outside_r(circle) and circle['movement'][0] > 0:
        circle['movement'][0] *= -1

    if outside_u(circle) and circle['movement'][1] < 0:
        circle['movement'][1] *= -1
    elif outside_d(circle) and circle['movement'][1] > 0:
        circle['movement'][1] *= -1


def make_circle(a, b, c, e):
    return {
        'color': a,
        'pos': b,
        'r': c,
        'movement': e
    }


def make_random_circle():
    movement = [random.randint(-5, 5), random.randint(-5, 5)]
    r, gr, b = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
    radius = random.randint(20, 50)
    pos = [random.randint(10, g.width-(radius+10)), random.randint(10, g.height-(radius+10))]
    return make_circle((r,gr,b), pos, radius, movement)


##########################################
# Exported Context                       #
##########################################

import pygame
import g
import polygon


class BallContext(EmptyContext):

    def __init__(self, *args, **kwargs):
        super(BallContext, self).__init__(*args, **kwargs)
        self.circles = [make_random_circle()]
        self.background = pygame.Surface(g.size)
        self.background.fill(g.background_rgb)

    def act(self, keymap):
        g.screen.blit(self.background, (0, 0))

        for circle in self.circles:

            circle['pos'][0] += circle['movement'][0]
            circle['pos'][1] += circle['movement'][1]
        
            if keymap.hold('u') and not outside_u(circle):
                circle['pos'][1] -= g.push_factor
            if keymap.hold('d') and not outside_d(circle):
                circle['pos'][1] += g.push_factor
            if keymap.hold('l') and not outside_l(circle):
                circle['pos'][0] -= g.push_factor
            if keymap.hold('r') and not outside_r(circle):
                circle['pos'][0] += g.push_factor

            update_movement(circle)
            pygame.draw.circle(g.screen, circle['color'], circle['pos'], circle['r'])
            
        if keymap.press('space'):
            self.circles.append(make_random_circle())

        if keymap.press('lshift'):
            keymap.set('switch')
            return polygon.PolygonContext()

    def setup(self):
        pass