#main entry and loop for the game

import sys, os
import pygame
from pygame.locals import *

import gfx, snd, data

#import playmode as firstplaymode
import playgame as firstplaymode



def rungame():
    fullscreen = 0 #1
    sound = 1
    if "-w" in sys.argv:
    	fullscreen = 0
    if "-q" in sys.argv:
    	sound = 0
    
    pygame.init()
    gfx.init(fullscreen)
    snd.init(sound)
    screen = gfx.screen

    img = gfx.image('loading.png')
    gfx.screen.blit(img, (0,0))
    pygame.display.update()
    preload()

    mode = firstplaymode.Play()

    clock = pygame.time.Clock()
    clockticked = 0
    while 1:
        #handle input
        for e in pygame.event.get():
            if e.type == QUIT:
                return
	    elif e.type == KEYDOWN:
		if e.key == K_p:
		    print 'SAVING "screenshot.tga"'
		    pygame.image.save(screen, 'screenshot.tga')
            mode.HandleEvent(e)

        #update and draw
        mode.Update(screen, clockticked)
        pygame.display.flip()

        #mode switches
        newmode = mode.GetNextMode()
        if newmode == -1:
            return
        if newmode:
            mode = newmode
            #transition.vertwipe(screen, mode)
        
        clockticked = clock.tick(data.maxfps)



def preload():
    modules = ['playmode', 'map', 'gui', 'playgame', 'village', 'huds',
    	       'sheep', 'dialog', 'sheperd']
    class Empty: pass
    for name in modules:
        mod = __import__(name)
        if hasattr(mod, 'images'):
            images = mod.images
            newimages = Empty()
	    newrawimages = Empty()
            for i in images:
                rawimg = gfx.rawimage(i + '.png')
		img = gfx.optimize(rawimg)
                setattr(newimages, i, img)
		setattr(newrawimages, i, rawimg)
            mod.images = newimages
	    mod.rawimages = newrawimages
        if hasattr(mod, 'sounds'):
            sounds = mod.sounds
            newsounds = Empty()
            for sound in sounds:
                s = snd.sound(sound + '.wav')
                setattr(newsounds, sound, s)
            mod.sounds = newsounds
        
	


USAGE = """Usage: %s [OPTION]

Options:
 -f, --fullscreen
    Selects fullscreen display (default)
 -w, --window
    Selects windowed display (not fullscreen)
 -s, --sound
    Allow in-game sounds (default)
 -ns, --nosound
    Disables in-game sounds

"""
