#!/usr/bin/python

import util;
from util import *;
import pygame
from pygame.locals import *
from Light import *
from PointLight import *
from random import *
from OpenGL.GL import *
from OpenGL.GLU import *
GL_CLAMP_TO_EDGE = 0x812F
from Player import *
import Alien
from Alien import *
import globalVars
import Crosshair
from HUD import *
from Crosshair import *
from Switch import *
from Door import *
from Health import *

from constants import *
from levels import *

count = 50

width = SWIDTH
height = SHEIGHT

groupTexts = 1

frames = 60
frameCount = 0
totalFrames = 0

texWidth = width * 1.0/maxTexSize
texHeight = height * 1.0/maxTexSize

pygame.init()
util.initializeDisplay(width, height)

bg = loadTexture('data/bg1.png')

pygame.event.set_grab(1)
pygame.mouse.set_visible(0)


player = Player()
globalVars.player = player

hud = HUD(player)



door = Door()

sprites = []
    
lights = []

for li in lights:
    globalVars.lightList.append(li)
    
globalVars.level = 0

def initLevel():
    globalVars.player.shots = []
    globalVars.alienList = []
    
    for i in range(0, levels[globalVars.level][0]):    
        guy = Alien()
        x = int(random() * (width- 32))
        y = int(random() * (height- 32))
        guy.set(x, y)
        globalVars.alienList.append(guy)
        
    globalVars.switches = []
    for i in range(0, levels[globalVars.level][1]):
        switch = Switch()
        x = int(random() * (width - 32))
        y = int(random() * (height - 32))
        switch.set(x,y)
        globalVars.switches.append(switch)
        
    globalVars.healthList = []
    for i in range(0, levels[globalVars.level][2]):
        health = Health()
        x = int(random() * (width - 32))
        y = int(random() * (height - 32))
        health.set(x,y)
        globalVars.healthList.append(health)
    
    

    x = int(random() * (width- 32))
    y = int(random() * (height- 32))
    player.set(x, y)
    
    door.isOpen = 0


def drawbg(tex):
    #global width, height
    glLoadIdentity()
    drawTile(width=SWIDTH, height=SHEIGHT, texture=tex)

def drawAliens(aliens,delta,player):
    
    dead = []
        
    for i in range(len(aliens)):
        if aliens[i].dead:
            dead.append(i)
            
        aliens[i].moveMe((player.x+player.width/2.0, player.y+player.height/2.0))
        aliens[i].update(delta)
        aliens[i].draw()
        
    for i in dead:
        aliens.pop(i)
        break # can only do 1 in a frame
        
        

def renderUnlit():
    glLoadIdentity()
    if (globalVars.bgtex != 0):
        setTex(globalVars.bgtex)
        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, maxTexSize, maxTexSize)
    else:
        globalVars.bgtex = glGenTextures(1)
        setTex(globalVars.bgtex)
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
        
        emptyList = "\x00" * maxTexSize*maxTexSize*4	
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, maxTexSize, maxTexSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, emptyList )
        
        glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, maxTexSize, maxTexSize, 0);

    glClear(GL_COLOR_BUFFER_BIT);
    


globalVars.done = 0

def exitGame(sigh):

    globalVars.done = 1
    
commands = {}
commands[KEYDOWN] = {}
commands[KEYUP] = {}
commands[KEYDOWN][K_ESCAPE] = (exitGame, None)
commands[KEYDOWN][K_w] = (player.move, 'up')
commands[KEYDOWN][K_s] = (player.move, 'down')
commands[KEYDOWN][K_a] = (player.move, 'left')
commands[KEYDOWN][K_d] = (player.move, 'right')
commands[KEYUP][K_w] = (player.stop,'up')
commands[KEYUP][K_s] = (player.stop,'down')
commands[KEYUP][K_a] = (player.stop,'left')
commands[KEYUP][K_d] = (player.stop,'right')
commands[MOUSEBUTTONDOWN] = player.startShoot
commands[MOUSEBUTTONUP] = player.stopShoot

crosshair = Crosshair()


clock = pygame.time.Clock()
clock.tick()
            
lastTime = pygame.time.get_ticks()

initLevel()

while globalVars.done != 1:
    delta = (clock.tick() / MS_PER_FRAME)
    event = pygame.event.poll()
    
    if event.type == KEYDOWN or event.type == KEYUP:
        defined = 0
        try:
            commands[event.type][event.key][0]
            defined = 1
        except:
            None
        if defined == 1:
            commands[event.type][event.key][0](commands[event.type][event.key][1])
    elif event.type == MOUSEBUTTONDOWN or event.type == MOUSEBUTTONUP:
        commands[event.type]()

    glClear(GL_COLOR_BUFFER_BIT)

    drawbg(bg)
    
    for switch in globalVars.switches:
        switch.draw()
    
    
    # start by going through the shots and finding the ones that have landed
    dead = []
    # go through once to find all the ones we need to kick out
    for i in range(len(globalVars.healthList)):
        if globalVars.healthList[i].dead:
            dead.append(i)
    
    for i in dead:
        globalVars.healthList.pop(i)              
        break # can only do 1 in a frame
        
    for health in globalVars.healthList:
        health.draw()
    
    drawAliens(globalVars.alienList,delta,player)

    renderUnlit()

    glLoadIdentity()
 
 
    door.draw()
    
    for myLight in lights:
        myLight.draw()

    player.update(delta)
    
    if player.dead:
        player.dead = 0
        globalVars.level = 0
        player.health = player.maxHealth
        initLevel()
    
    allFlipped = 1
    for switch in globalVars.switches:
        if not switch.flipped:
            allFlipped = 0
            break
    
    if allFlipped:
        door.isOpen = 1
    
    if door.isOpen:
        if circleCollide(player, door, 20):
            globalVars.level += 1
            initLevel()
    
    globalVars.mouseX, globalVars.mouseY = pygame.mouse.get_pos()
    crosshair.update(delta)
    
    hud.draw()
    
    pygame.display.flip()

    """frameCount += 1
    totalFrames += 1
    if frameCount == frames:
        thisTime = pygame.time.get_ticks() 
        print "fps:  %.2f" % ((frameCount*1000.0)/(thisTime - lastTime))
        lastTime = thisTime
        frameCount = 0"""
