#!/usr/bin/env python2

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2018 NIWA & British Crown (Met Office) & Contributors.
#
# 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] [USER_AT_HOST]
gcylc [OPTIONS] [REG] [USER_AT_HOST]

This is the cylc Graphical User Interface.

The USER_AT_HOST argument allows suite selection by 'cylc scan' output:
  cylc gui $(cylc scan | grep <suite_name>)

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>/etc/gcylc.rc.eg to ~/.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(forward_x11=True):
        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__, comms=True, noforce=True, jset=True, argdoc=[
            ('[REG]', 'Suite name'),
            ('[USER_AT_HOST]', 'user@host:port, shorthand for --user, --host '
             '& --port.')])

    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 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")

    suite = None
    if len(args) > 0:
        suite = args[0]
    if len(args) == 2:
        try:
            user_at_host, options.port = args[1].split(':')
            options.owner, options.host = user_at_host.split('@')
        except ValueError:
            print >> sys.stderr, ('USER_AT_HOST must take the form '
                                  '"user@host:port"')
            sys.exit(1)
    ControlApp(
        suite, options.owner, options.host,
        options.port, options.comms_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))
