#!/usr/bin/env python

import sys
import os

import matplotlib
matplotlib.use('PDF') # We cannot use Qt4Agg since it interferes with pyqt apps 

import pylab
pylab.ioff()

try:
    from PyQt4 import QtGui, QtCore, QtWebKit
except ImportError:
    print "ERROR: The MMLF GUI requires the PyQt4 package. You may use "\
          "run_mmlf.py instead, however."
    sys.exit(0)

import mmlf
from mmlf.gui.explorer import MMLFExplorer
from mmlf.gui.experimenter import MMLFExperimenter
                
class MMLF_GUI(QtGui.QMainWindow):
    """ The main window of the MMLF GUI.
    
    Contains subtabs for the MMLF Explorer, the MMLF Experimenter and the
    Documentation.
    """    
    
    # A signal for indicating that an exception has occurred  
    exceptionOccurredSignal = \
                QtCore.pyqtSignal(basestring, name='exceptionOccurredSignal')
 
    def __init__(self, parent=None):
        super(MMLF_GUI, self).__init__(parent)
        
        self.resize(1024, 768)
        self.setWindowTitle('Maja Machine Learning Framework')
        
        self.tabWidget = QtGui.QTabWidget(self)
        self.tabWidget.setTabsClosable(False)
        self.explorerTab = MMLFExplorer(self)
        self.tabWidget.addTab(self.explorerTab, "Explorer")
        self.experimenterTab = MMLFExperimenter(self)
        self.tabWidget.addTab(self.experimenterTab, "Experimenter")        
        self.documentationTab = QtWebKit.QWebView(self)
        # Look for documentation 
        if os.path.exists("./doc/_build"): # Relative to current directory
            self.documentationTab.load(QtCore.QUrl("./doc/_build/html/index.html"))
        elif sys.platform == 'linux2' and os.path.exists("/usr/share/doc/mmlf"): # Absolute directory
            self.documentationTab.load(QtCore.QUrl("/usr/share/doc/mmlf/index.html"))
        else: # On the web
            self.documentationTab.load(QtCore.QUrl("http://mmlf.sourceforge.net/"))
        self.tabWidget.addTab(self.documentationTab, "Documentation")
        
        self.tabWidget.setCurrentWidget(self.explorerTab)

        self.setCentralWidget(self.tabWidget)
        
        # Implement proper shutdown
        self.connect(self, QtCore.SIGNAL('quit()'), self.closeEvent)
        
    def closeEvent(self, event):
        self.explorerTab.tearDown()
        self.experimenterTab.tearDown()
        
        super(MMLF_GUI, self).closeEvent(event)
        
    def _exceptionOccurred(self, exceptionString):
        ret = QtGui.QMessageBox.warning(self, "Exception", exceptionString)
            

if __name__ == '__main__':
    mmlf.setupConsoleLogging(level="info")
    
    # Initialize MMLF rw area
    mmlf.initializeRWArea()
      
    #Creating Qt application
    app = QtGui.QApplication(sys.argv)
 
    mmlfGUI = MMLF_GUI()
    mmlfGUI.show()
 
    #Initing application
    sys.exit(app.exec_())
    