"""Actions menu for map editor"""
"""Adventures on Planet Zephulor by Aaron Hachez. 

   All code, artwork, and sound copyright 2003, Aaron Hachez.

   ----------------------------------------------------------------------------------------

   This file is part of "Adventures on Planet Zephulor".

   A copy of the GNU General Public License should be included with any
   redistribution of this program in a file named "COPYING.txt".

   "Adventures on Planet Zephulor" is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   "Adventures on Planet Zephulor" is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with "Adventures on Planet Zephulor"; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

   ----------------------------------------------------------------------------------------

   "Adventures on Planet Zephulor" uses the following libraries:

   PyGame
   SDL

   Both are at the time of this writing, licensed under the GNU LGPL. Please see
   the included file LGPL for details 
"""


import pygame
import myimg
import Tkinter
from random import Random

class App(Tkinter.Frame):
    def __init__(self, master=None, itemlist=[0,0,0,0,0,0,0]):
        Tkinter.Frame.__init__(self, master)
        self.pack()

        self.label1 = Tkinter.Label(text="Tile Attributes (pass, pass left, pass top, pass right, pass bottom, damage, slow)")
        self.label1.pack()

        # Get how many attributes we are going to be working with.
        attribsize = len(itemlist)

        self.entry = []

        # For all attribute ellements
        for i in range(attribsize):
            # Add new element to array
            self.entry.append(Tkinter.Entry())
            # Pack item
            self.entry[i].pack()

        self.contents = []

        # here is the application variable
        for i in range(attribsize):
            self.contents.append(Tkinter.StringVar())
        
        for i in range(attribsize):
            self.contents[i].set(itemlist[i])

        # tell the entry widget to watch this variable
        for i in range(attribsize):
            self.entry[i]["textvariable"] = self.contents[i]

        # and here we get a callback when the user hits return.
        # we will have the program print out the value of the
        # application variable when the user hits return
        #self.entry.bind('<Key-Return>', self.savecontents)
        
#    def savecontents(self, event):
#        self.container = self.contents.get()
#        self.initial_focus = None
#        self.destroy()

    def get(self):

        list = []

        for item in self.contents:
            list.append(int(item.get()))

        return(list)


class domenu_base:
    """Main actions/do menu class"""

    # The display rect for the tile menu
    viewport = []

    # The width and height of the viewport
    viewportwidth = 0
    viewportheight = 0

    # The tile image of the currently selected image
    tile = None

    # The tiles currently selected for placement
    selected = []

    # The map id of the tile to replace
    tiletorep = 0
    
    # The tiles currently selected for placement
    selattrib = []

    # Where to draw the currently selected tile (Note, for multiple tiles, only the first is drawn
    selectedx = 15
    selectedy = 495

    # The text of the attributes for the currently selected map tile
    attributetext = " "

    # The map coords
    mapinfotext = " "

    # The current status message
    statustext = " "

    def __init__(self, viewrect=[ 0,0,0,0 ], tileimage=None):
        """Initialize the tile menu"""

        self.viewport = viewrect[:]

        self.viewportwidth = self.viewport[2] - self.viewport[0]
        self.viewportheight = self.viewport[3] - self.viewport[1]

        self.tile = tileimage
        self.selected = [0]

        self.background = pygame.Surface((self.viewportwidth, self.viewportheight))
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

    def draw(self, screen):
        """Draw the do menu to the screen"""
        
        screen.blit(self.background, (self.viewport[0], self.viewport[1]))

        # Text used to describe tiles selected
        tiletext = " "

        # Draw the selected tile to the screen
        if self.selected[0] >= 0:
            screen.blit(self.tile, (self.selectedx, self.selectedy))
            tiletext = `len(self.selected)` + " menu items selected"
        elif self.selected[0] == -1:
            tiletext = "ERASE"
        elif self.selected[0] == -2:
            tiletext = "INVISIBLE"
        elif self.selected[0] == -3:
            tiletext = "END LVL"
        elif self.selected[0] == -4:
            tiletext = "NPC BLOCK"

        self.make_txt(screen, text=tiletext, xy=(60, 505))
        self.make_txt(screen, text=self.attributetext, xy=(292, 505))
        self.make_txt(screen, text=self.statustext, xy=(15, 532))
        self.make_txt(screen, text=self.mapinfotext, xy=(15, 555))

    def getclick(self, object):
        """Check to see if click is within our viewport"""

        # If the object is not less than right side, greater than left side,
        # Less than top, or greater than bottom
        if object.screenrect[0] > self.viewport[2]:
            return
        elif object.screenrect[1] > self.viewport[3]:
            return
        elif object.screenrect[0] < self.viewport[0]:
            return
        elif object.screenrect[1] < self.viewport[1]:
            return
        else:
            # If we get to this point, the object is onscreen
            return 1

    def returnpos(self, object):
        """Return what tile has been clicked"""

        # Get x/y values from the distance of the mouse pointer (object) from the upper x/y of the viewport
        x = object.screenrect[0] - self.viewport[0]
        y = object.screenrect[1] - self.viewport[1]

        # As long as our x/y values are within the proper range
        if x < self.viewportwidth and y < self.viewportheight and x > 0 and y > 0:
            xy = (x, y)
            return xy
        else:
            return

    def update(self):
        """Make updates for each cycle"""

        pass

    def addselected(self, tile, attributes=[], tileimage=None, clear=0):
        """Add a tile to the selected list (From menu)"""

        # Make sure that this tile hasn't already been added to the list
        for n in self.selected:
            if n == tile:
                return

        # If clear, then reset the list
        if clear:
            self.selected = []
            self.selattrib = []

        if tile >= 0:
            self.tile = tileimage

        self.selattrib = attributes
        self.selected += [tile]

    def returnselected(self, seed):
        """Return a random tile from the selected list. If the list is only one, return that one"""

        rnd = Random(seed)

        # Get a number that is somewhere between 0 and the max length of our selected list
        tileid = rnd.uniform(0, len(self.selected))

        return int(tileid)

    def make_txt(self, screen, text=" ", xy=(0, 0)):
        """Print text at x/y."""

        if pygame.font:
            font = pygame.font.Font(None, 24)
            text = font.render(text, 1, (210, 210, 210))
            textpos = text.get_rect()
            screen.blit(text, (xy[0], xy[1]))

    def getattributes(self, attributes=[]):
        """Prompt user for new attributes for tile, and return them, if no attributes passed, return null"""

        # If any attributes are passed in, else return null
        if attributes:        
            myapp = App(itemlist=attributes)
            myapp.mainloop()

            return(myapp.get())
        else:
            return

    def parseattributes(self, attributes=[]):
        """Parse passed in attributes and return a human readable string"""

        text = ""

        if attributes:
   
            if attributes[0]:
                text += "Pass(P), "
    
            if attributes[1]:
                text += "Pass(L), "
    
            if attributes[2]:
                text += "Pass(T), "
            
            if attributes[3]:
                text += "Pass(R), "
            
            if attributes[4]:
                text += "Pass(B), "
            
            if attributes[5]:
                text += "Dmg(D)=" + `attributes[5]`
            
            if attributes[6]:
                text += "Slow(S)=" + `attributes[6]`
            
            # If no text, there weren't any attributes flagged
            if text == "":  
                text += "No attributes set"

        else:
            text += "Non-Attributable tile type"

        self.attributetext = text
