#!/usr/bin/env python

# example menu.py

import os
import string

import pygtk
pygtk.require('2.0')
import gtk

#def restart_audio(widget):
#    print 'restart audio!'
#    os.system('/usr/local/bin/restart-audio')

class Filename:
    def __init__(self, pathname):
        self.pathname = pathname
        if pathname.startswith('dvd:'):
            self.filename = pathname
        else:
            fields = self.pathname.split('/')
            self.filename = fields[-1].strip()
        self.lower_filename = self.filename.lower()
        self.filename_with_doubled_underscores = self.filename.replace('_', '__')

    def __cmp__(self, other):
        if self.lower_filename < other.lower_filename:
            return -1
        elif self.lower_filename > other.lower_filename:
            return 1
        else:
            return 0

class GG_Menu:
    def __init__(self):
        # create a new window
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(800, 200)
        window.set_title("GG Menu")
        window.connect("delete_event", lambda w,e: gtk.main_quit())

        self.movie = ''
        self.player = ''
        self.prior_dir = ''
        #self.prior_file = ''

        # Init the menu-widget, and remember -- never
        # show() the menu widget!! 
        # This is the menu that holds the menu items, the one that
        # will pop up when you click on the "Root Menu" in the app
#        restart_audio_button = gtk.Button('Restart Audio')
#        restart_audio_button.connect('pressed', restart_audio)
#        restart_audio_button.show()
        player_menu = gtk.Menu()

        # Next we make a little loop that makes three menu-entries for
        # "test-menu".  Notice the call to gtk_menu_append.  Here we are
        # adding a list of menu items to our menu.  Normally, we'd also
        # catch the "clicked" signal on each of the menu items and setup a
        # callback for it, but it's omitted here to save space.
        #pipe = os.popen("find ~/movie -type f -print | egrep '/1/.*\.mkv$|/1/.*\.mp4$|/1/.*\.avi$'")
#        pipe = os.popen("find ~/movie -follow -type f -print | egrep '/.*\.mkv$|/.*\.mp4$|/.*\.avi$|/.*\.ogm'")
#        filenames = [ Filename(line.rstrip()) for line in pipe ]
#        pipe.close()
        #print filenames
#        filenames.sort()
#        filenames.append(Filename('dvd://'))
#        for filename in filenames:
            # Copy the names to the buf.
#            pathname = filename.pathname

            # Create a new menu-item with a name...
#            movie_menu_items = gtk.MenuItem(filename.filename_with_doubled_underscores)

            # ...and add it to the menu.
#            movie_menu.append(movie_menu_items)

            # Do something interesting when the menuitem is selected
#            movie_menu_items.connect("activate", self.movie_menuitem_response, filename)

            # Show the widget
#            movie_menu_items.show()

        #for player in [ 'mplayer -vo sdl -ao alsa "%s"', \
        for player in [ 'mplay "%s"', \
            'xine -V xshm -A alsa "%s"', \
            'totem "%s"', \
            'gnome-mplayer "%s"', \
            'smplayer "%s"', \
            'vlc "%s"' ]:
            # Copy the names to the buf.
            buf = player

            # Create a new menu-item with a name...
            player_menu_items = gtk.MenuItem(buf)

            # ...and add it to the menu.
            player_menu.append(player_menu_items)

            # Do something interesting when the menuitem is selected
            player_menu_items.connect("activate", self.player_menuitem_response, buf)

            # Show the widget
            player_menu_items.show()

        # This is the root menu, and will be the label
        # displayed on the menu bar.  There won't be a signal handler attached,
        # as it only pops up the rest of the menu when pressed.
        #root_menu = gtk.MenuItem("Root Menu")

        #root_menu.show()

        # Now we specify that we want our newly created "menu" to be the
        # menu for the "root menu"
        #root_menu.set_submenu(movie_menu)
        #root_menu.set_submenu(player_menu)

        # A vbox to put the menus and a button in:
        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()

        # Create a menu-bar to hold the menus and add it to our main window
        menu_bar = gtk.MenuBar()
        vbox.pack_start(menu_bar, False, False, 2)
        menu_bar.show()

        # put in the restart audio button
#        vbox.pack_start(restart_audio_button, True, True, 2)

        # Create a button to which to attach the player menu
        self.player_button = gtk.Button("Select player")
        self.player_button.connect_object("event", self.player_button_press, player_menu)
        vbox.pack_end(self.player_button, True, True, 2)
        self.player_button.show()

        # Create a button to which to attach the movie menu
        self.movie_button = gtk.Button("Select movie")
        #self.movie_button.connect_object("event", self.button_press, self.movie_chooser)
        self.movie_button.connect_object("event", self.movie_button_press, None)
        vbox.pack_end(self.movie_button, True, True, 2)
        self.movie_button.show()

        # And finally we append the menu-item to the menu-bar -- this is the
        # "root" menu-item I have been raving about =)
        #menu_bar.append (root_menu)

        # always display the window as the last step so it all splashes on
        # the screen at once.
        window.show()

    # Respond to a button-press by posting a menu passed in as widget.
    #
    # Note that the "widget" argument is the menu being posted, NOT
    # the button that was pressed.
    def player_button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            # Tell calling code that we have handled this event the buck
            # stops here.
            return True
        # Tell calling code that we have not handled this event pass it on.
        return False

    def movie_button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS:
            self.movie_chooser = gtk.FileChooserDialog(title=None,
                action=gtk.FILE_CHOOSER_ACTION_OPEN,
                buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
            self.movie_chooser.set_default_size(1280, 1024)
            if self.prior_dir == '':
                self.movie_chooser.set_current_folder(os.path.expanduser('~/movie'))
#            else:
#                self.movie_chooser.set_current_folder(os.path.expanduser(self.prior_dir))
            if self.movie != '':
                self.movie_chooser.set_filename(self.movie)

            self.movie_chooser.show()

            response = self.movie_chooser.run()
            if response == gtk.RESPONSE_OK:
                self.movie = self.movie_chooser.get_filename()
                self.movie_button.set_label(self.movie.replace('_', '__'))
                self.prior_dir = os.path.dirname(self.movie)
                #self.prior_file = os.path.basename(self.movie)
                print self.movie, 'selected'
            elif response == gtk.RESPONSE_CANCEL:
                print 'Closed, no files selected'
                self.movie_chooser.destroy()
                return

            self.movie_chooser.destroy()

            self.possible_play()

            # Tell calling code that we have handled this event
            return True
        # Tell calling code that we have not handled this event pass it on.
        return False

#    def movie_menuitem_response(self, widget, filename):
#        self.movie = filename.pathname
#        self.movie_button.set_label(filename.filename_with_doubled_underscores)
#        #print "movie %s" % movie
#        self.possible_play()

    def player_menuitem_response(self, widget, player):
        self.player = player
        self.player_button.set_label(player)
        #print "player %s" % string
        self.possible_play()

    def possible_play(self):
        print 'in possible_play, player is %s, movie is %s' % (self.player, self.movie)
        if self.player != '' and self.movie != '':
            os.system(self.player % self.movie)

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    GG_Menu()
    main()