#gfx

import pygame
from pygame.locals import *

import data

screen = None
res = None

def init(full):
    global screen, res
    res = data.resolution
    if full:
    	flags = FULLSCREEN
    else:
    	flags = 0

    #find best depth and set display mode
    best_depth = pygame.display.mode_ok(res, 16, flags)
    if not best_depth and full:
        full = 0
        flags = get_video_flags(full)
        best_depth = pygame.display.mode_ok(res, 16, flags)
    screen = pygame.display.set_mode(res, flags, best_depth)
    res = screen.get_rect()

    pygame.display.set_caption(data.windowtitle, data.icontitle)
    return screen


def get_video_flags(fullscreen):
    if fullscreen: return FULLSCREEN
    return 0



#image loading

def rawimage(name):
    fullname = data.find_file('images', name)
    if not fullname:
    	raise IOError, "Cannot find image for "+name
    return pygame.image.load(fullname)

def optimize(image):
    if image.get_alpha():
    	newimage = pygame.Surface(image.get_size())
    	newimage.fill((255,0,255))
    	newimage.blit(image, (0, 0))
    	newimage.set_colorkey((255, 0, 255), RLEACCEL)
	image = newimage
    elif image.get_colorkey():
    	image.set_colorkey(image.get_colorkey(), RLEACCEL)
    
    return image.convert()

def image(name):
    return optimize(rawimage(name))


dither_image = None
def ghost(image):
    global dither_image
    if not dither_image:
    	dither_image = rawimage('dither.png')
	dither_image.set_colorkey((255, 255, 255))
    newimage = image.convert()
    cc = newimage.get_colorkey()
    if not cc: cc = 0, 0, 0
    else: cc = cc[:3]
    dither_image.set_palette([cc])
    newimage.blit(dither_image, (0, 0))
    newimage.set_colorkey(cc)
    return newimage
    
    
    

def position(img, **position):
    "position(img, center=(100,100))"
    r = img.get_rect()
    corner, pos = position.popitem()
    setattr(r, corner, pos)
    return r

