import sys
import pygame
import math

import globals
import ball
import flipper
import element
import table

import anim

import Player

# ==================================================================
# Need to setup some basic state control here!!! do ASAP!

pygame.init()
pygame.key.set_repeat(20, 20)

size = (600, 760)
balls = [ball.Ball((380, 573))]

flippers = [
        flipper.Flipper((104, 688), 50, "l", [0, 0]), 
        flipper.Flipper((200, 688), 50, "r", [0, 0]), 
        flipper.Flipper((184, 329), 50, "l", [80, -359])
    ]
    
elements = [
        element.Element((131, 188), 30), 
        element.Element((228, 196), 30),
        element.Element((190, 272), 30)
    ]

table = table.Table(size, balls, flippers, elements)
globals.screen = pygame.display.set_mode(table.size)

# set the initial screen gfx
globals.screen.blit(table.tabletop[0], [0,0])
pygame.display.flip()

#initialises table elements and such
table.Init()

currtime = 0
oldtime = 0

#--------------------------------------------------------------------
# Main loop Starts
#--------------------------------------------------------------------

done = 0
while (done == 0):
    # Simple millisecond frame timer 
    # - build a fps counter so we can deteremine some basic perf.
    oldtime = currtime
    currtime = pygame.time.get_ticks()
    ms = currtime - oldtime
    
#    pygame.time.wait(1)
    
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_z:
                table.activate_left()
            if event.key == pygame.K_SLASH:
                table.activate_right()
            if event.key == pygame.K_SPACE:
                table.PullLauncher()
            if event.key == pygame.K_RETURN:
                table.Init()
            if event.key == pygame.K_q:
                done = 1
            if event.key == pygame.K_ESCAPE:
                done = 1
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_z:
                table.deactivate_left()
            if event.key == pygame.K_SLASH:
                table.deactivate_right()
            if event.key == pygame.K_SPACE:
                table.ReleaseLauncher()

    # Update the Table
    table.Update(ms)
           
    table.draw(ms)
    
    pygame.display.flip()

#--------------------------------------------------------------------
# Main loop complete
#--------------------------------------------------------------------

# some cleanup
table.Shutdown()

sys.exit()