#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2002-2011
# The MeqTree Foundation &
# ASTRON (Netherlands Foundation for Research in Astronomy)
# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This program 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.
#
# This program 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 this program; if not, see <http://www.gnu.org/licenses/>,
# or write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

if __name__ == "__main__":
    from optparse import OptionParser
    import traceback
    import TigGUI
    import Tigger
    import TigGUI.kitties.utils
    from PyQt4.Qt import QApplication, QColor, QMessageBox

    import TigGUI.init

    _verbosity = TigGUI.kitties.utils.verbosity(name="startup")
    dprint = _verbosity.dprint
    dprintf = _verbosity.dprintf

    # parse options is the first thing we should do

    usage = "usage: %prog [options] <sky models or FITS files>"
    parser = OptionParser(usage=usage)
    parser.add_option("-d", "--debug",dest="verbose",type="string",action="append",metavar="Context=Level",
                      help="(for debugging Python code) sets verbosity level of the named Python context. May be used multiple times.")
    parser.add_option("-T", "--timestamps",action="store_true",
                      help="(for debugging Python code) enable timestamps in debug output")
    (options, rem_args) = parser.parse_args()

    if options.timestamps:
      try:
        TigGUI.kitties.utils.verbosity.enable_timestamps()
      except:
        pass
    dprint(1,"starting up")

    # setup include path
    import sys
    import os.path
    # TigGUI lives here for now. Add it to include path so that "import TigGUI" works
    sys.modules['TiggerMain'] = __name__

    Tigger.nuke_matplotlib();  # don't let the door hit you in the ass, sucka

    print("Welcome to Tigger " + TigGUI.release_string)
    print("Please wait a second while the GUI starts up.")

    dprint(1,"imported TigGUI")
    TigGUI.startup_dprint = dprint
    TigGUI.startup_dprintf = dprintf


    dprint(1,"imported Qt4")
    app = QApplication(sys.argv)
    app.setDesktopSettingsAware(True)
    from TigGUI.init import pixmaps
    app.setWindowIcon(pixmaps.tigger_starface.icon())
    # Need for PlotStyles colors -- ignore error on non-X11 platforms like the Mac
    try:
        QColor.setAllowX11ColorNames(True)
    except AttributeError:
        pass

    dprint(1,"created QApplication")
    #splash = QSplashScreen(TigGUI.pixmaps.tigger_splash.pm())
    #splash.showMessage("Welcome to TigGUI!",Qt.AlignHCenter|Qt.AlignBottom)
    #splash.show()

    import TigGUI.Images
    import TigGUI.MainWindow
    dprint(1,"imported TigGUI.MainWindow")
    import TigGUI.Tools

    # although this seems unused, it is actually registering these plugins
    from TigGUI.Tools import export_karma,add_brick,make_brick,restore_image

    dprint(1,"imported TigGUI.Tools")
    mainwin = TigGUI.MainWindow.MainWindow(None)
    dprint(1,"created main window")

    import sys
    if sys.version_info[0] < 3:  
      sunset_notice = \
        "This is the last major release for Python 2.x\n"\
        "It is provided AS-IS. We recommend that you\n"\
        "upgrade to Python 3.6+ and upgrade to Tigger\n"\
        "1.6+"
    else:
      sunset_notice = \
        "This major release targets Python 2.x\n"\
        "We see you are running Python >= 3. We \n"\
        "recommend that you upgrade to Python 3.6+ \n"\
        "and upgrade to Tigger 1.6+\n"
    print("-----------------------------------------------\n"\
          "Sunset notice:\n"\
          "-----------------------------------------------")
    print(sunset_notice)
    print("-----------------------------------------------")
    QMessageBox.warning(mainwin, "Sunset notice", sunset_notice, QMessageBox.Ok)
    
  # add optional tools
    for name,callback in TigGUI.Tools.getRegisteredTools():
      mainwin.addTool(name,callback)
    dprint(1,"added optional tools")

    # parse remaining args
    images = [arg for arg in rem_args if TigGUI.Images.isFITS(arg)]
    models = [ arg for arg in rem_args if arg not in images ]

    if len(models) > 1:
      parser.error("Only one model should be specified at the command line.")

    # load images first
    for img in images:
      print("Loading image" + img)
      #splash.showMessage("Loading image %s"%img,Qt.AlignHCenter|Qt.AlignBottom)
      mainwin.loadImage(img)
      dprint(1,"loaded image",img)

    # load model, if specified
    for mod in models:
      print("Loading model" + mod)
      try:
        mainwin.openFile(mod,show=False)
      except:
        traceback.print_exc()
        print("Error loading model %s"%mod)
        os._exit(0)

      #splash.showMessage("Loading model %s"%mod,Qt.AlignHCenter|Qt.AlignBottom)
      dprint(1,"loaded model",mod)

    # start updating the plot
    mainwin.enableUpdates()
    dprint(1,"started plot updates")

    # flush app event queue, so windows get resized , etc.
    app.processEvents()

    # handle SIGINT
    def sigint_handler (sig,stackframe):
      print("Caught Ctrl+C, exiting...")
      mainwin.close()


    import signal
    signal.signal(signal.SIGINT,sigint_handler)
    dprint(1,"added signal handler")

    #splash.finish(mainwin)

    app.exec_()
