#!/usr/bin/python

#   Copyright (C) 2002-2003 Yannick Gingras <ygingras@ygingras.net>
#   Copyright (C) 2002-2003 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
from OBBApp.PatEditor     import PatEditor
from OBBGui.OBBSkin       import OBBSkin
from OBBFuncts            import kickApp
from qt                   import *

try:
    import psyco
except ImportError:
    # At least we tried !
    pass

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
        self.verbose       = 0
        self.skinToCompile = []

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

    def parseOptions(self):
        try:
            opts, self.args = getopt.getopt( self.args,
                                             'hVpvc:',
                                             [ "help",
                                               "version",
                                               "demo-pat-editor=",
                                               "profile",
                                               "verbose",
                                               "compile="] )
        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
            if opt in ("-p", "--profile"):
                self.profiling = 1
            if opt in ("-v", "--verbose"):
                self.verbose = 1
            if opt in ("-c", "--compile"):
                self.needVersion = 1
                self.skinToCompile.append(arg)
        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()

        for skinFile in self.skinToCompile:
            self.compileSkin(skinFile)

        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
        -v, --verbose       enable debug mode
        -c, --compile SKIN  compile the images of skin SKIN

        Demo Options :
        --demo-pat-editor DELAY  load the patter editor in demo mode
        """
    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 = PatEditor( self.patEditorDemoDelay, self.verbose )
        app.exec_loop()

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

    def compileSkin(self, skinFile):
        app = QApplication(self.args)
        skin = OBBSkin()
        skin.compile(skinFile)
        kickApp(app)
    

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

def runProfiler():
    import profile, pstats

    filename = tempfile.mktemp() # FIXME : 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:
        try:
            # psycho choke when profiling
            psyco.background()
        except NameError:
            pass
        main()
