#!/usr/bin/python

import gtk
import hildon
import os


# Pointer to the last clicked button
last_clicked_button = None

# Callabck to set last clicked button
def clicked(button, binary):
	os.system(binary)
	

def create_table(): 
    
    # create a table of 10 by 10 squares.
    table = gtk.Table (4, 7, False)
    
    # set the spacing to 10 on x and 10 on y
    table.set_row_spacings(5)
    table.set_col_spacings(5)

    table.show()
    
    i = 0;
    j = 0;
    puzzlebin = os.path.realpath("/opt/sgt-puzzles/puzzles")
    for dirname, dirnames, filenames in os.walk('/usr/games/'):
        for gamename in sorted(filenames):
            gamebin = os.path.join(dirname, gamename)
            if os.path.islink(gamebin):
                 target = os.path.realpath(gamebin)
                 if target == puzzlebin:
                      image="/opt/sgt-puzzles/pixmaps/" + gamename + ".xpm"
                      if os.path.isfile(image):
                           vbox = gtk.VBox()
                           label = gtk.Label(gamename) 
                           button = gtk.Button()
                           imagewidget = gtk.Image()
                           imagewidget.set_from_file(image)
                           vbox.add(imagewidget)
                           vbox.add(label)
                           button.add(vbox)
                           button.connect("clicked", clicked, gamebin)
                           table.attach(button, i, i+1, j, j+1)
                           if i >= 3:
                              i = 0
                              j = j+1
                           else:
                              i = i+1
                           

    return table

def app_quit(widget, data=None): 
    gtk.main_quit()
    
def main():
    window = hildon.StackableWindow()
    window.set_title("Puzzles")
    pannable_area = hildon.PannableArea()
    
    window.connect("destroy", app_quit)
        
    pannable_area.set_property("mov-mode", hildon.MOVEMENT_MODE_VERT)
            
    table = create_table()
    table.set_property("homogeneous", True)

    # pack the table into the scrolled window
    pannable_area.add_with_viewport(table)

    # Create a box and pack the widgets into it
    vbox = gtk.VBox(False, 0)

    vbox.pack_start(pannable_area, True, True, 0)

    # Add the box into the window
    window.add(vbox)

    window.show_all()
    gtk.main()

if __name__ == "__main__":
    main()
