#!/usr/bin/python

#   Copyright (C) 2002 Yannick Gingras <ygingras@ygingras.net>
#   Copyright (C) 2002 Vincent Barbin <vbarbin@openbeatbox.org>

#   This file is part of Open Beat Box.

#   Open Beat Box 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.

#   Open Beat Box 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 Open Beat Box; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import config
import getopt
import sys
import tempfile
import os
from OBBApp.PatEditorDemo import PatEditorDemo

class OBBProcess:
    def __init__(self, args):
        self.args = args
        self.exitStatus = 0 # no prob
        self.initOptions()

    def initOptions(self):
        self.needUsage   = 0
        self.needVersion = 0
        self.needHelp    = 0
        self.dontStart   = 0
        self.profiling   = 0

        # demo stuff
        self.patEditorDemo       = 0
        self.patEditorDemoDelay  = 0
        
        self.parseOptions()

    def parseOptions(self):
        try:
            opts, self.args = getopt.getopt( self.args,
                                             'hVp',
                                             [ "help",
                                               "version",
                                               "demo-pat-editor=",
                                               "profile"] )
        except getopt.GetoptError:
            self.needUsage = 1
            self.exitStatus = 2 # big prob
            opts=[]
        
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                self.needHelp = 1
                self.needUsage = 1
            if opt in ("-V", "--version"):
                self.needVersion = 1
            if opt in ("--demo-pat-editor",):
                self.patEditorDemo = 1
                self.patEditorDemoDelay = int(arg)
                # since it may be fast or not working, at
                # least print the version
                self.printVersion = 1
                self.dontStart = 1
            if opt in ("-p", "--profile"):
                self.profiling = 1

        if self.needVersion or self.needHelp or self.needUsage:
            self.dontStart = 1
                

    def run(self):
        # help and info
        if self.needVersion:
            self.printVersion()
        if self.needUsage:
            self.printUsage()
        if self.needHelp:
            self.printHelp()

        # demos
        if self.patEditorDemo:
            self.startPatEditorDemo()

        # real fun : )
        if not self.dontStart:
            self.startProcessing()
            
        return self.exitStatus

    def printHelp(self):
        print """
        General Option : 
        -h, --help     print this information and exit
        -V, --version  print version and exit
        -p, --profile  enable profiling

        Demo Options :
        --demo-pat-editor DELAY  load the patter editor demo
        """
    def printUsage(self):
        print """Usage : obb [OPTION]
        Try 'obb --help' for more information."""

    def printVersion(self):
        print config.LONG_NAME + " version " + config.VERSION

    def startProcessing(self):
        # TODO load the real OBB
        app = PatEditorDemo( self.patEditorDemoDelay )
        app.exec_loop()

    def startPatEditorDemo(self):
        app = PatEditorDemo( self.patEditorDemoDelay )
        app.exec_loop()

        
def main():
    sys.exit(OBBProcess(sys.argv[1:]).run())

def runProfiler():
    import profile, pstats
    
    filename = tempfile.mktemp() # dangerous !
    profile.run("main()", filename)

    p = pstats.Stats(filename)
    p.sort_stats('calls').print_stats()
    p.sort_stats('cumulative').print_stats()
    p.sort_stats('time').print_stats()

    os.remove(filename)
        
if __name__ == '__main__':
    if ("-p" in sys.argv) or ("--profile" in sys.argv):
        runProfiler()
    else:
        main()
