#!/usr/bin/env python

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2016 NIWA
#
# 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 3 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/>.

"""cylc gui [OPTIONS] [REG]
gcylc [OPTIONS] [REG]

This is the cylc Graphical User Interface.

Local suites can be opened and switched between from within gcylc. To connect
to running remote suites (whose passphrase you have installed) you must
currently use --host and/or --user on the gcylc command line.

Available task state color themes are shown under the View menu. To customize
themes copy $CYLC_DIR/conf/gcylcrc/gcylc.rc.eg to $HOME/.cylc/gcylc.rc and
follow the instructions in the file.

To see current configuration settings use "cylc get-gui-config".

In the graph view, View -> Options -> "Write Graph Frames" writes .dot graph
files to the suite share directory (locally, for a remote suite). These can
be processed into a movie by \$CYLC_DIR/dev/bin/live-graph-movie.sh=."""

import sys
if '--use-ssh' in sys.argv[1:]:
    sys.argv.remove('--use-ssh')
    from cylc.remote import remrun
    if remrun().execute():
        sys.exit(0)

import os
from cylc.option_parsers import CylcOptionParser as COP
import cylc.flags
from cylc.templatevars import load_template_vars


def main():
    sys.path.append(
        os.path.dirname(
            os.path.realpath(os.path.abspath(__file__))) + '/../lib')
    sys.path.append(
        os.path.dirname(os.path.realpath(os.path.abspath(__file__))) + '/../')

    parser = COP(__doc__, pyro=True, noforce=True, jset=True,
                 argdoc=[('[REG]', 'Suite name')])

    parser.add_option(
        "-r", "--restricted",
        help="Restrict display to 'active' task states: submitted, "
        "submit-failed, submit-retrying, running, failed, retrying; "
        "and disable the graph view.  This may be needed for very large "
        "suites. The state summary icons in the status bar still "
        "represent all task proxies.",
        action="store_true", default=False, dest="restricted")

    (options, args) = parser.parse_args()

    # import modules that require gtk now, so that a display is not needed
    # just to get command help (e.g. when running make on a post-commit hook
    # on a remote repository).

    import gtk
    import warnings
    warnings.filterwarnings('ignore', 'use the new', Warning)
    from cylc.gui.app_gcylc import ControlApp

    # Make current working directory be $HOME. Otherwise (1) if the user
    # attempts to start gcylc from a CWD that has been removed, Pyro will
    # not be importable below; and (2) if the CWD gets removed later while
    # gcylc is running, subprocesses spawned by gcylc will fail when they
    # attempt to determine their CWD.
    os.chdir(os.environ['HOME'])

    gtk.settings_get_default().set_long_property(
        "gtk-toolbar-icon-size", gtk.ICON_SIZE_SMALL_TOOLBAR, "main")
    gtk.settings_get_default().set_long_property(
        "gtk-button-images", True, "main")
    gtk.settings_get_default().set_long_property(
        "gtk-menu-images", True, "main")

    if len(args) == 1:
        suite = args[0]
    else:
        suite = None
    app = ControlApp(
        suite, options.db, options.owner, options.host,
        options.port, options.pyro_timeout,
        load_template_vars(options.templatevars, options.templatevars_file),
        options.restricted)
    gtk.main()


if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        if cylc.flags.debug:
            raise
        sys.exit(str(exc))
