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

import gooeypy as gui
from gooeypy.const import *

HELPTEXT="""
new level
    to create a new level, use
    '-new [size]' where size is two integers (for the number of
    fields in x and y direction) seperated by a 'x'.
    example: "editor.py -new 14x9"

edit level
    to load and edit a level, type
    "- load [path]" where path is a path to a
    valid levelfile
"""
def cmd():
    args = sys.argv
    if len(args) != 3 or args[1] not in ("-new", "-load"):
        print HELPTEXT
    else:
        if args[1] == "-new":
            try:
                x, y = map(int, args[2].split("x"))
                run(action="new", arg=(x, y))
            except:
                print "invalid size argument, type -h for help"
        elif args[2] == "-load":
            if os.path.isfile(args[2]):
                run(action="load", arg=args[2])
            else:
                print args[2], " is not a file!"




pygame.init()
screen = pygame.display.set_mode((700, 400))
FIELD_SIZE = 42 # auf prozentual umstellen
WIDTH = 10
HEIGHT = 8
XOFFSET, YOFFSET = 30, 30

def l(name, resize = (FIELD_SIZE, FIELD_SIZE), colorkey=-1):
    if name=="empty":
        image = pygame.surface.Surface((FIELD_SIZE,FIELD_SIZE))
        #image.fill(250,250,250)
        #image.set_colorkey(
    else:
        fullname = os.path.join('/home/julian/Python/tests/pygame/mouserunner/', name+".gif")
        try:
            image = pygame.image.load(fullname)
        except pygame.error, message:
            print 'Cannot load image:', fullname
            raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    if resize:
        image = pygame.transform.scale(image, resize)
    return image

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('data', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error, message:
        print 'Cannot load sound:', fullname
        raise SystemExit, message
    return sound

IMAGES = {"bg":{
                            "#":l("stone"),
                            " ":l("grass")},
                  "fg":{"0":l("empty")},
                  "item":{
                            "/":l("carrot"),
                            "W":l("wolf"),
                            "X":l("player"),
                            "0":l("empty")}
                }
NAMES = {"#":"Stone",
                  " ":"Grass",
                  "0":"None",
                  "/":"Carrot",
                  "W":"Wolf",
                  "X":"Player",
                  }

def pti(pos):
    "pixel to index"
    x, y = pos
    x, y = x-XOFFSET, y-YOFFSET
    fz = FIELD_SIZE
    #print "pti: ", int(0.5*fz)
    return (x-int(0.5*fz))/fz, (y-int(0.5*fz))/fz

def itp(pos):
    "index to pixel"
    x, y = pos
    fz = FIELD_SIZE
    return fz*(x+0.5)+XOFFSET, fz*(y+0.5)+YOFFSET








class Field(pygame.sprite.Sprite):
    selected = [" ", "0", "0"]
    def __init__(self, pos, bgc = None, itemc=None, fgc=None):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.surface.Surface((FIELD_SIZE, FIELD_SIZE))
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.layers = [bgc, itemc, fgc]


    def update(self):
        self.image.fill((0,0,0))
        for i, k in enumerate(("bg", "item", "fg")):
            if self.rect.collidepoint(pygame.mouse.get_pos()):
                c = self.selected[i]
            else:
                c = self.layers[i]
            if c:
                self.image.blit(IMAGES[k][c], (0,0))

  #  def edit(self):
        if self.rect.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
                self.layers = self.selected[:]

                print "edited"


class Map(dict):
    def __init__(self, allsprites, groups):
        dict.__init__(self)
        #self.width, self.height = width, height
        self.allsprites  = allsprites
        self.groups = groups




    def load_level(self, name):
                print "loading level ", name
                leveltext = file(name, "r").read()
                i = 0
                for block in leveltext.split("\n\n"):
                    x = 0
                    y = 0
                    layer = ("bg", "item", "fg")[i]
               #     print "NEW BLOCK"
                 #   print block
                    for c in block:
                            if c == "\n":
                                    y+=1
                                    x = 0
                            elif c != "0":
                                    #print x, y, c
                                    fx, fy =  itp((x, y))

                                    img = IMAGES[layer][c]

                                    #self.allsprites.add(field)
                                    #self.groups[layer].add(field)

                                    if i == 0:
                                        field  = Field((fx, fy), bgc=c)
                                        self.allsprites.add(field)
                                        self[(x,y)] = field
                                    elif i==1:
                                        self[(x,y)].itemc = c
                                    else:
                                        self[(x,y)].fgc = c
                                    x+=1
                            else:
                                    x += 1
                    i += 1
                print "end loading"





def main():
    """this function is called when the program starts.
       it initializes everything it needs, then runs in
       a loop until the function returns."""
#Initialize Everything
    pygame.init()
    screen = pygame.display.set_mode((700, 400))
    pygame.display.set_caption('title')

   # gui
    gui.init(myscreen=screen)
    fx, fy = (FIELD_SIZE)*WIDTH+2*XOFFSET, (FIELD_SIZE)*HEIGHT+2*YOFFSET
    print fx, fy

    app = gui.App(width=700, height=400)
    container = gui.Container(x=fx, y=YOFFSET,width=200, height=400)
    app.add(container)
    tb = gui.TextBlock(value="This is my simple level editor using python, pygame and gooepy for gui.", width=150)
    #def get_data():
    #    return "test"
    #l = gui.Label(get_data, align="center", y=70, font_size=25, color=(255,255,255))
    slider = gui.VSlider(x=tb.width, y= tb.height, value=tb.height,
                                                      min_value=tb.height-100, length=200, step = 20)


    b = gui.VBox(y=slider.link("value"), width=tb.width)
    container.add(tb,  b)
    container.add(slider)
    selectboxes = list()
    for key, value in (("bg", "BackgroundFields"),("item", "Items"), ("fg", "ForegroundFiels")):
        l = gui.Label(value)
        s = gui.SelectBox(multiple=False)
        selectboxes.append(s)
        b.add(l, s)
        for c, img in IMAGES[key].iteritems():

            #i = gui.Image(img)
            #print type(img), type(i)

            #label = gui.Label(NAMES[c])
            s.add(NAMES[c], c)
            #if not s.selected:
                #print s.values
             #   help(s.options)
                #first = s.options.keys()[0]
                #help(first)
                #first.focussed = True
                #s.selected.add(first)
                #print s.values
                #s.draw()

    select = gui.SelectBox(y=tb.height, width=tb.width, scrollable=True)
    for i in range(10):
        select.add("test%i"%i, i)

    #print help(b)



   # help(container)
  #  pygame.mouse.set_visible(0)

#Create The Backgound
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    #pygame.draw.rect(background, (250,0,0), (0,380,640,400))

#Put Text On The Background, Centered
    #if pygame.font:
    #    font = pygame.font.Font(None, 36)
    #    text = font.render(":)", 1, (10, 10, 10))
    #    textpos = text.get_rect(centerx=background.get_width()/2)
    #    background.blit(text, textpos)

#Display The Background
    screen.blit(background, (0, 0))
    pygame.display.flip()

#Prepare Game Objects
    clock = pygame.time.Clock()

#    boom_sound = load_sound('boom.wav')


    allsprites = pygame.sprite.RenderPlain()
    groups = {"fg":pygame.sprite.Group(),
                      "bg":pygame.sprite.Group(),
                      "item":pygame.sprite.Group()}
    map = Map(allsprites, groups)
    map.load_level("/home/julian/Python/tests/pygame/mouserunner/test.level")



#Main Loop
    while 1:
        clock.tick(100)

        for i, box in enumerate(selectboxes):
            if box.values:
                l = box.values.pop()
                Field.selected[i] = l


    #Handle Input Events
        events = pygame.event.get()
        for event in events:
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
            #elif event.type == MOUSEBUTTONDOWN and event.button==1:
             #   print "click"
           #     try:
         #           x, y = pti(event.pos)
       #             map[(x, y)].edit()
     #           except KeyError:
   #                 pass

        allsprites.update()
        #print s.selected

    #Draw Everything
        #screen.blit(background, (0, 0), pygame.rect.Rect(0,0,150,200))
        allsprites.draw(screen)
        groups["bg"].draw(screen)
        groups["item"].draw(screen)
        groups["fg"].draw(screen)
        pygame.display.flip()


        app.run(events)
       # app.dirty = True
        app.draw()

        gui.update_display()

#Game Over


#this calls the 'main' function when this script is executed
if __name__ == '__main__': main()#cmd()
 

