# -=- encoding: utf-8 -=-

"""This file holds the PresentationModule class, which is the base
class for any presentation module.


"""
import os
import time
import gtkdrive

HOME = os.environ['HOME']

# Keypress detection stuff
BUTTON = '/tmp/btntrigger'
if os.path.exists(BUTTON):
    os.unlink(BUTTON)

def wait_next():
    while True:
        time.sleep(0.1)
        if os.path.exists(BUTTON):
            os.unlink(BUTTON)
            break

# import presentation modules
class PresentationModule(object):
    # Default value for basename
    basename = '/tmp/'

    def __init__(self):
        """Start the required apps.  Might depend on preceding module."""
        pass

    def present(self, title, desc=None):
        print "-" * 80
        print "NEXT SLIDE: %s" % title
        print desc

    def wait_next(self):
        print "************** WAITING FOR BUTTON PRESS **************"
        wait_next()

    def loop_events(self):
        events = [x[6:] for x in dir(self) if x.startswith('event_')] + \
                 ['quit', 'cancel', '']
        print "Looping through available events:"
        for x in events:
            print "   %s" % x
        def genvals():
            while True:
                import commands
                ev = commands.getoutput('python gtkdrive.py')
                if ev in events:
                    return ev
        while True:
            wait_next()
            ev = genvals()
            if ev == 'quit':
                return
            elif ev in ['cancel', '']:
                continue
            else:
                print "Calling event %s" % ev
                getattr(self, 'event_%s' % ev)()

    def event(self, name, doc):
        #
        # Every event should be pretty fail safe, it should test whether
        # programs are available, open new ones if required.
        #
        # We're not using events for apps switching, unless there's something
        # new required
        #
        if hasattr(self, 'event_%s' % name):
            print '-' * 60
            print "EVENT:", name
            print "   %s" % doc
        else:
            print "WARNING: UNIMPLEMENTED EVENT:", name

    # def event_something(self):
    #     do something [sample]

    def beep(self):
        """Make sure to modprobe pcspkr, and install the `beep` package"""
        os.system("beep")

    def terminate(self):
        """Kill all process and shutdown the module"""
        pass

    def extract_tar(self, package, version):
        """Extract a pre-loaded .tar.gz under the basename for the
        current presentation module.

        This will extract the package `package` in ~/package

        It will also leave a trace file, to make sure it manages that
        directory, when the time comes to delete it.
        """
        tarfile = os.path.join(self.basename, 'tars',
                               "%s-%s.tar.gz" % (package, version))
        if not os.path.exists(tarfile):
            print "WARNING, TARFILE %s DOESN'T EXIST! CONTINUING..." % tarfile
        else:
            print "EXTRACTING %s ..." % tarfile,
            os.system('cd ~; tar -zxf "%s"' % tarfile)
            print " DONE"
            os.system("cd ~; touch %s/.pypresmodule" % package)

    def clean_extracted_tar(self, package):
        """This will clean-up the directory created with the extraction of
        a .tar.gz using extract_tar()"""
        if os.path.exists("%s/%s/.pypresmodule" % (HOME, package)) and \
                HOME and package:
            os.system("rm -rf %s/%s" % (HOME, package))
        
