#!/usr/bin/python
#http://stackoverflow.com/questions/11513132/embedding-ipython-qt-console-in-a-pyqt-application/11525205#11525205
# http://stackoverflow.com/questions/11513132/embedding-ipython-qt-console-in-a-pyqt-application/11940456#11940456

import sys
import os
import traceback
from goose import *
from PyQt4 import Qt, QtCore, QtGui
from PyQt4.QtGui import *
import imp
import signal
from time import *

GOOSE_ROOT_DIRECTORY    = os.path.expanduser("~/.goose/")
GOOSE_LOG               = "logs"
GOOSE_VERSION           = goose.VERSION
GOOSE_RUN_TIME          = strftime("%Y%m%d%H%M%S%Z", localtime())

GOOSE_LOG_DIRECTORY = os.path.join( GOOSE_ROOT_DIRECTORY
                                  , GOOSE_VERSION
                                  , GOOSE_LOG
                                  , GOOSE_RUN_TIME
                                  )

# def excepthook(exception_class, exception, tb):
#     CRITICAL('{0}: {1}'.format(exception_class.__name__, exception))
#     CRITICAL("\n" + "".join(traceback.format_tb(tb)))
#     sys.exit()

def moose_exists():
    try:
        imp.find_module('moose')
        return True
    except ImportError:
        return False

def main():
    # sys.excepthook = excepthook
    if not os.path.exists(GOOSE_LOG_DIRECTORY):
        os.makedirs(GOOSE_LOG_DIRECTORY)
    application = QApplication(sys.argv)
    application.setWindowIcon(QIcon(goose.APPLICATION_ICON_PATH))
    if not moose_exists():
        QMessageBox.critical( None
                            , "Where is MOOSE?"
                            , """I cannot find MOOSE.
Are you sure you installed MOOSE? Maybe MOOSE is installed in a nonstandard location and python cannot find it.
Please make sure that MOOSE is visible to your python
installation before running me."""
                            )
        sys.exit(0)
    window =  MainWindow(application, GOOSE_LOG_DIRECTORY ,sys.argv[1:])
    window.setWindowState(QtCore.Qt.WindowMaximized)
    # signal.signal(signal.SIGINT, lambda * args : window.quit_slot() )
    signal.signal(signal.SIGINT, window.stop_moose_servers)
    signal.signal(signal.SIGTERM, window.stop_moose_servers)

    window.show()

    sys.exit(application.exec_())

if __name__ == "__main__":
    main()
