'''Game main module.

Contains the entry point used by the run_game.py script.

Feel free to put all your game code here, or in other modules in this "lib"
directory.
'''

import sys
import os
import math

import getopt
import time
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame, pygame.image
from pygame.locals import *

MAX_FRAME_RATE=60


import fsm_mgr
import texMgr
import tubeMgr
import crate
import state_main_menu
import state_intro
import state_splash_bdg
import state_splash_pyweek
import voiceover

def resize((width, height)):
    if height==0:
        height=1
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluOrtho2D(0,800,0,600)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def init():
    glEnable(GL_TEXTURE_2D)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glShadeModel(GL_SMOOTH)
    glClearColor(0.9, 0.9, 1.0, 1.0)

    fsm_mgr.pushState(state_main_menu.StateMainMenu())
    fsm_mgr.pushState(state_intro.StateIntro())
    fsm_mgr.pushState(state_splash_pyweek.StateSplashPyWeek())
    fsm_mgr.pushState(state_splash_bdg.StateSplashBDG())


    


def update(ms):
    seconds=ms/1000.0

    return fsm_mgr.update(seconds)

def draw():
    glClear(GL_COLOR_BUFFER_BIT)

    fsm_mgr.draw()
    #state_main_menu.draw()
    
    #tubeMgr.draw()

def handleKey(k, unicode):
    if unicode=="|":
        crate.cheat(1)
        
    fsm_mgr.handleKey(k,unicode)

def handleMouseButton(bDown, button):
    fsm_mgr.handleMouseButton(bDown, button)


def main():
    flagDict={"windowed":True}

    video_flags = OPENGL|DOUBLEBUF
    if not flagDict["windowed"]:
        video_flags = video_flags|FULLSCREEN

    pygame.init()

    sz=800,600
    surface = pygame.display.set_mode(sz, video_flags)

    resize(sz)


    pygame.display.set_caption("Woody Tigerbaum's Twisted Marble Factory","WT2")
    surface = pygame.image.load("data/icon.png")
    pygame.display.set_icon(surface)

    #pygame.mouse.set_visible(False)
    pygame.mouse.set_pos((sz[0]/2,sz[1]/2))

    voiceover.findfiles()
    voiceover.select_character("tess")
    voiceover.select_random_channel()
    
    init()

    frames = 0
    ticks = pygame.time.get_ticks()
    myClock=pygame.time.Clock()

    global MAX_FRAME_RATE
    myClock.tick(MAX_FRAME_RATE)

    timeToQuit=False
    isActive=True

    
    while 1:
        #the amount of milliseconds that a loop MUST run
        loopMinTime=1000/MAX_FRAME_RATE
        
        # note - this doesn't work well by itself. At the bottom of
        # the loop, I add in an additional sleep
        ms=myClock.tick(MAX_FRAME_RATE)
        loopTopTime=pygame.time.get_ticks()

        for event in pygame.event.get():
            if (event.type == QUIT):
                #(event.type == KEYDOWN and event.key == K_ESCAPE) or
                #(event.type == KEYDOWN and event.key == K_F4)):
                timeToQuit=True
                break

            if event.type == KEYDOWN:
                handleKey(event.key, event.unicode)

            elif event.type == MOUSEBUTTONDOWN:
                handleMouseButton(True, event.button)
            elif event.type == MOUSEBUTTONUP:
                handleMouseButton(False, event.button)

            elif event.type == KEYUP:
                global controlKey
                controlKey = ''

            elif ((sys.platform=="win32") and
                  (event.type==ACTIVEEVENT)):
                if event.state==6:
                    fsm_mgr.handleActivate(True)
                    """
                    if flagDict["mouseGrab"]:
                        pygame.event.set_grab(True)
                    pygame.mouse.set_visible(False)
                    """
                    isActive=True
                elif event.state==2:
                    fsm_mgr.handleActivate(False)
                    """
                    if flagDict["mouseGrab"]:
                        pygame.event.set_grab(False)
                    pygame.mouse.set_visible(True)
                    """
                    isActive=False


            
        if timeToQuit:
            break


        if isActive:
            if not update(loopMinTime):
                timeToQuit=True
            voiceover.update(loopMinTime/1000.0)

                
        draw()
        pygame.display.flip()
        frames = frames+1
        loopBottomTime=pygame.time.get_ticks()
        loopElapsedTime=loopBottomTime-loopTopTime
        timeLeft=loopMinTime-loopElapsedTime

        if timeLeft>10:
            MAX_FRAME_RATE += 0.1
            if MAX_FRAME_RATE>100.0:
                MAX_FRAME_RATE=100.0
            pygame.time.wait(int(timeLeft-5))
        elif timeLeft>0:
            pygame.time.wait(1)
        else:
            MAX_FRAME_RATE -= 1.0
            if MAX_FRAME_RATE<10.0:
                MAX_FRAME_RATE=10.0


    #print "fps:  %d" % ((frames*1000)/(pygame.time.get_ticks()-ticks))


