"""Char menu for map editor. This menu displays a list of thumbnail images for characters and loads their associated data (imagefile, datafile, and id)"""

"""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 os
import pickle

class charmenu_base:
    """Main charmenu class"""

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

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

    # The starting offset for drawing
    startoffset = 0

    # The value to scroll by each cycle, if not 0, menu will scroll
    scrollvalue = 0

    # The tile images
    tiles = []

    # The tile image data
    tiledata = []

    # A list of the filenames for chars
    charfiles = []

    # Pad is the distance between tiles
    pad = 2

    # The background so you cannot see the map behind the menu
    background = None

    def __init__(self, viewrect=[ 0,0,0,0 ], charlist="default.charlist"):
        """Initialize the char menu"""

        self.viewport = viewrect[:]

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

        self.loadlist(charlist)

        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 char menu to the screen"""

        screen.blit(self.background, (self.viewport[0], self.viewport[1]))

        x = 0
        y = 0

        # Set our start position to the offset
        n = self.startoffset

        y = self.viewport[1]

        # For each item in the list
        for i in range(len(self.tiles)):

            #y = self.viewport[1]

            # If our y coord is greater than viewport total height 
            if (y + self.tiledata[i][1]) > self.viewport[3]:
                break
            # Elif current tile is greater or equal to total length of tile list
            elif n >= len(self.tiles):
                break

            x = self.viewport[0]
            x += self.pad
               
            # Blit the tile to the screen
            screen.blit(self.tiles[ n ], (x, y))
                
            y += self.tiledata[i][1]
            y += i * self.pad

            n += 1

    def loadlist(self, filename):
        """Load character data, primarily first sprite image, and create a serial number for said char"""

        # Setup os independant path to file
        fullname = os.path.join('../data', filename)

        try:
            # Open file for write
            f = file(fullname, 'r')
        except:
            self.status = "Error opening file " + `filename` + " for read."
            return None

        # Now pickle the data
        # Load the character list
        #self.charlist = pickle.load(f)

        #print self.charlist

        self.charlist = []

        for line in f:
            # Strip off the trailing newline if there is one
            if line[len(line) - 1] == '\n':
                line = line[0:(len(line) - 1)]

            self.charlist.append(line)
            self.loadchar(line)

        # Close file
        f.close()

#        # For each entry in the character list
#        for item in self.charlist:
#            # Load the character file, and then get tile data
#            self.loadchar(item)
            

    def loadchar(self, filename):
        """Load character data/image(s) from file"""

        # Setup os independant path
        fullname = os.path.join('../data', filename)

        try:
            # Open file for read
            f = file(fullname, 'r')
        except:
            self.status = "Error opening file " + `filename` + " for read."
            return

        # Get the image file attributes (numtiles=0, colorkey=-1, tilewidth=32, tileheight=32, top=0, left=0, bottom=0, right=0)
        imagefileattrib = pickle.load(f)

        # Get the name of the image file (The second thing in the character file)
        imagefile = pickle.load(f)

        # because we have a number of things we need to specify about the tiles, and we only load
        # one at a time, we do loading here, rather than in a seperate function
        self.tiles += myimg.loadtiles(imagefile, numtiles=0, tilewidth=imagefileattrib['tilewidth'], \
                                        tileheight=imagefileattrib['tileheight'], colorkey=0) 

        # Record the width and height for this tile
        self.tiledata += [ [ imagefileattrib['tilewidth'], imagefileattrib['tileheight'] ] ]

        # Add this char filename to list
        self.charfiles += [filename]
        
        f.close()


    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 returntile(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
        wherex = object.screenrect[0] - self.viewport[0]
        wherey = object.screenrect[1] - self.viewport[1]

        # As long as our x/y values are within the proper range
        if wherex < self.viewportwidth and wherey < self.viewportheight and wherex > 0 and wherey > 0:

            x = 0
            y = 0
    
            # Set our start position to the offset
            n = self.startoffset

            # If wherey > y, thisone points to the current tile,
            # when wherey is less than y, break, i.e. thisone still points to last tile
            thisone = 0

            y = self.viewport[1]

            # For each item in the list
            for i in range(len(self.tiles)):
    
    
                x = self.viewport[0]
                x += self.pad

                # If our y coord is greater than viewport total height
                if (y + self.tiledata[i][1]) > self.viewport[3]:
                    break

                if wherey > y:
                    thisone = n
                else:
                    break
                   
                n += 1
    
                y += self.tiledata[i][1]
                y += i * self.pad

            tile = thisone

            return tile
        else:
            return

    def scroll(self, value=0):
        """Scroll the tile menu up and down"""

        # Scroll value number of rows.
        self.startoffset += value

        if self.startoffset < 0:
            self.startoffset = 0

        if self.startoffset > len(self.tiles):
            self.startoffset = len(self.tiles)

        self.scrollvalue = value

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

        if self.scrollvalue != 0:
            self.scroll(self.scrollvalue)
