#/usr/bin/env python
"""
This simple example is used for the line-by-line tutorial
that comes with pygame. It is based on a 'popular' web banner.
Note there are comments here, but for the full explanation, 
follow along in the tutorial.
"""


#Import Modules
import os, pygame
from pygame.locals import *

if not pygame.font: print 'Warning, fonts disabled'


#functions to create our resources
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    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)
    return image, image.get_rect()

#classes for our game objects
class Tile(pygame.sprite.Sprite):
    """moves a clenched fist on the screen, following the mouse"""
    def __init__(self, x, y, image, rect):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image, self.rect = image, rect
        self.posx = x
        self.posy = y

    def update(self, worldx, worldy):
        self.posx = self.posx - worldx
        self.posy = self.posy - worldy
        self.rect.topleft = self.posx, self.posy
        "move the fist based on the mouse position"
        #pos = pygame.mouse.get_pos()
        #self.rect.midtop = pos
        #if self.punching:
        #    self.rect.move_ip(5, 10)


class World:
    """moves a monkey critter across the screen. it can spin the
       monkey when it is punched."""
    def __init__(self, columns, rows):
        self.groundSurface = pygame.Surface((columns*32,rows*32))
        self.groundSurface.set_colorkey((0,255,0))
        self.groundSurface.fill((0,0,0))

        self.column = columns
        self.row = rows 

        groundTile0, gTile0rect = load_image('groundTile0.gif')
        for j in xrange(rows):
            for i in xrange(columns):
                self.groundSurface.blit(groundTile0, (i*32,j*32))       

        self.tileSurface = pygame.Surface((columns*32,rows*32))
        self.tileSurface.set_colorkey((0,255,0))
        self.tileSurface.fill((0,255,0))

        self.itemSurface = pygame.Surface((columns*32,rows*32))
        self.itemSurface.set_colorkey((0,255,0))
        self.itemSurface.fill((0,255,0))

        self.monsterSurface = pygame.Surface((columns*32,rows*32))
        self.monsterSurface.set_colorkey((0,255,0))
        self.monsterSurface.fill((0,255,0))

        self.menuSurface = pygame.Surface((60,480))
        self.menuSurface.fill((255,255,255))

        self.worldx = 0
        self.worldy = 0

        self.currentSelection = 0
        self.currentLayer = 0

        self.layerCount = []
        self.layerCount.append(2) # 2 ground
        self.layerCount.append(4) # 4 tiles
        self.layerCount.append(1) # 1 item
        self.layerCount.append(1) # 1 monster

        self.groundInfo = []
        self.tileInfo = []
        self.itemInfo = []
        self.monsterInfo = []
        for j in xrange(rows):
            curLine = ''
            for i in xrange(columns):
                curLine = curLine[0:i] + '0' + curLine[(i+1):]
            self.groundInfo.append(curLine)
            self.tileInfo.append(curLine)
            self.itemInfo.append(curLine)
            self.monsterInfo.append(curLine)

    def update(self):
        "walk or spin, depending on the monkeys state"
        pos = pygame.mouse.get_pos()
        scrollSpeed = 5
        if pos[0] < 50:
            if self.worldx < 0:
                self.worldx = self.worldx + scrollSpeed
        elif pos[0] > 590 and pos[0] < 640:
            if self.worldx > -(self.column*32)+640:
                self.worldx = self.worldx - scrollSpeed
        if pos[1] < 50:
            if self.worldy < 0:
                self.worldy = self.worldy + scrollSpeed
        elif pos[1] > 430:
            if self.worldy > -(self.row*32)+480:
                self.worldy = self.worldy - scrollSpeed

    def draw(self, screen):
        #Put Text On The Background, Centered
        screen.blit(self.groundSurface, (self.worldx, self.worldy))
        screen.blit(self.tileSurface, (self.worldx, self.worldy))
        screen.blit(self.itemSurface, (self.worldx, self.worldy))
        screen.blit(self.monsterSurface, (self.worldx, self.worldy))
        screen.blit(self.menuSurface, (640,0))
        if pygame.font:
            font = pygame.font.Font(None, 20)
            text = font.render("Level", 1, (0, 0,0))
            textpos = (645,20)
            screen.blit(text, textpos)
            text = font.render("Editor", 1, (0, 0, 0))
            textpos = (643, 32)
            screen.blit(text, textpos)
            text = font.render("Layer:", 1, (0, 0, 0))
            textpos = (643, 70)
            screen.blit(text, textpos)
            text = font.render("Tile:", 1, (0, 0, 0))
            textpos = (643, 110)
            screen.blit(text, textpos)
            if self.currentLayer == 0:
                text = font.render("Ground", 1, (0, 0, 0))
                textpos = (645, 82)
                screen.blit(text, textpos)
                if self.currentSelection == 0:
                    text = font.render("GreyDirt", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
                elif self.currentSelection == 1:
                    text = font.render("BloodDirt", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
            elif self.currentLayer == 1:
                text = font.render("Tiles", 1, (0, 0, 0))
                textpos = (645, 82)
                screen.blit(text, textpos)
                if self.currentSelection == 0:
                    text = font.render("Wall", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
                elif self.currentSelection == 1:
                    text = font.render("RedTile", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
                elif self.currentSelection == 2:
                    text = font.render("UpTile", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
                elif self.currentSelection == 3:
                    text = font.render("DownTile", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
            elif self.currentLayer == 2:
                text = font.render("Items", 1, (0, 0, 0))
                textpos = (645, 82)
                screen.blit(text, textpos)
                if self.currentSelection == 0:
                    text = font.render("RedKey", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)
            elif self.currentLayer == 3:
                text = font.render("Monsters", 1, (0, 0, 0))
                textpos = (645, 82)
                screen.blit(text, textpos)
                if self.currentSelection == 0:
                    text = font.render("LizardMan", 1, (0, 0, 0))
                    textpos = (645, 122)
                    screen.blit(text, textpos)

    def upLayer(self):
        self.currentLayer = ( self.currentLayer + 1 ) % 4
        self.currentSelection = 0

    def downLayer(self):
        self.currentLayer = ( self.currentLayer - 1 ) % 4
        self.currentSelection = 0

    def upSelection(self):
        self.currentSelection = ( self.currentSelection + 1) % self.layerCount[self.currentLayer] #something?

    def downSelection(self):
        self.currentSelection = ( self.currentSelection - 1) % self.layerCount[self.currentLayer] #something?

    def addTile(self):
        lizard, lizardrect = load_image('lizardmanB1.gif',-1)
        groundTile0, gTile0rect = load_image('groundTile0.gif')
        groundTile1, gTile1rect = load_image('groundTile1.gif')
        redTile1, rTile1rect = load_image('redTile1.gif')    
        upTile1, upTile1rect = load_image('upTile1.gif',-1)
        downTile1, downTile1rect = load_image('downTile1.gif')
        wallTile1, wallTile1rect = load_image('wallTile1.gif')
        blank, blankrect = load_image('blank.gif')
        redKey, redKeyrect = load_image('redKey1.gif',-1)
        tile = 0

        pos = pygame.mouse.get_pos()
        if pos[0] < 640:
            print "Placing tile at " + str((pos[0]/32)*32) + ", " + str((pos[1]/32)*32)
            curRow = int((pos[1]-self.worldy)/32)
            curCol = int((pos[0]-self.worldx)/32)
            if self.currentLayer == 0:
                if self.currentSelection == 0: # ground tile
                    tileChar = '0'
                    tile = groundTile0
                elif self.currentSelection == 1:
                    tileChar = '1'
                    tile = groundTile1
                self.groundInfo[curRow] = str(self.groundInfo[curRow][0:curCol]) + tileChar + str(self.groundInfo[curRow][curCol+1:])
                self.groundSurface.blit(tile,(curCol*32, curRow*32))
            elif self.currentLayer == 1:
                if self.currentSelection == 0:
                    tileChar = 'W'
                    tile = wallTile1
                elif self.currentSelection == 1:
                    tileChar = 'R'
                    tile = redTile1
                elif self.currentSelection == 2:
                    tileChar = 'U'
                    tile = upTile1
                elif self.currentSelection == 3:
                    tileChar = 'D'
                    tile = downTile1
                self.tileInfo[curRow] = str(self.tileInfo[curRow][0:curCol]) + tileChar + str(self.tileInfo[curRow][curCol+1:])
                self.tileSurface.blit(tile,(curCol*32, curRow*32))
            elif self.currentLayer == 2:
                if self.currentSelection == 0:
                    tileChar = 'R'
                    tile = redKey
                self.itemInfo[curRow] = str(self.itemInfo[curRow][0:curCol]) + tileChar + str(self.itemInfo[curRow][curCol+1:])
                self.itemSurface.blit(tile,(curCol*32, curRow*32))
            elif self.currentLayer == 3:
                if self.currentSelection == 0:
                    tileChar = 'L'
                    tile = lizard
                self.monsterInfo[curRow] = str(self.monsterInfo[curRow][0:curCol]) + tileChar + str(self.monsterInfo[curRow][curCol+1:])
                self.monsterSurface.blit(tile,(curCol*32, curRow*32))

    def delTile(self):
        pos = pygame.mouse.get_pos()
        if pos[0] < 640:
            print "Deleting tile at " + str((pos[0]/32)*32) + ", " + str((pos[1]/32)*32)
            curRow = int((pos[1]-self.worldy)/32)
            curCol = int((pos[0]-self.worldx)/32)
            blank, blankrect = load_image('blank.gif')
            groundTile0,null = load_image('groundTile0.gif')
            tile = 0
            if self.currentLayer == 0:
                tile = groundTile0
            else:
                tile = blank
            if self.currentLayer == 0:
                self.groundInfo[curRow] = str(self.groundInfo[curRow][0:curCol]) + '0' + str(self.groundInfo[curRow][curCol+1:])
                self.groundSurface.blit(tile,(curCol*32, curRow*32))
            elif self.currentLayer == 1:
                self.tileInfo[curRow] = str(self.tileInfo[curRow][0:curCol]) + '0' + str(self.tileInfo[curRow][curCol+1:])
                self.tileSurface.blit(tile,(curCol*32, curRow*32))
            elif self.currentLayer == 2:
                self.itemInfo[curRow] = str(self.itemInfo[curRow][0:curCol]) + '0' + str(self.itemInfo[curRow][curCol+1:])
                self.itemSurface.blit(tile,(curCol*32, curRow*32))
            elif self.currentLayer == 3:
                self.monsterInfo[curRow] = str(self.monsterInfo[curRow][0:curCol]) + '0' + str(self.monsterInfo[curRow][curCol+1:])
                self.monsterSurface.blit(tile,(curCol*32, curRow*32))

    def saveMap(self):
        print "Saved to newfloor.txt!"
        filename = "newfloor.txt"
        FILE = open(filename,"w")
        FILE.write("Floor X - \'You fill this in!\'\n")
        FILE.write("Ground\n")
        for lines in self.groundInfo:
            FILE.write(lines+"\n")
        FILE.write("Tiles\n")
        for lines in self.tileInfo:
            FILE.write(lines+"\n")
        FILE.write("Items\n")
        for lines in self.itemInfo:
            FILE.write(lines+"\n")
        FILE.write("Monsters\n")
        for lines in self.monsterInfo:
            FILE.write(lines+"\n")
        FILE.close()
        

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, 480))
    pygame.display.set_caption('Death Tower - Level Editor Private Release v0.1')
    pygame.mouse.set_visible(1)

#Prepare Game Objects
    clock = pygame.time.Clock()
    cworld = World(25,25)

#Main Loop
    while 1:
        clock.tick(60)

    #Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
                elif event.key == K_DOWN:
                    cworld.downLayer()
                elif event.key == K_UP:
                    cworld.upLayer()
                elif event.key == K_LEFT:
                    cworld.downSelection()
                elif event.key == K_RIGHT:
                    cworld.upSelection()
                elif event.key == 115 or event.key == 304: # 's' or 'S'
                    cworld.saveMap()
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    cworld.addTile()
                elif event.button == 3:
                    cworld.delTile()
            elif event.type is MOUSEBUTTONUP:
                null = 0

        cworld.update()
    #Draw Everything
        cworld.draw(screen)
        pygame.display.flip()

#Game Over


#this calls the 'main' function when this script is executed
if __name__ == '__main__': main()


