#!/usr/bin/env python

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2017 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 gscan [OPTIONS]

This is the cylc scan gui for monitoring running suites on a set of
hosts.

To customize themes copy $CYLC_DIR/conf/gcylcrc/gcylc.rc.eg to
$HOME/.cylc/gcylc.rc and follow the instructions in the file."""

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

import gtk
import warnings
warnings.filterwarnings('ignore', 'use the new', Warning)

gtk.settings_get_default().set_long_property(
    "gtk-button-images", True, "main")
gtk.settings_get_default().set_long_property(
    "gtk-menu-images", True, "main")

from cylc.gui.gscan import ScanApp
from cylc.option_parsers import CylcOptionParser as COP
from cylc.suite_host import get_user


def main():
    """Implement "cylc gscan"."""
    parser = COP(
        __doc__,
        comms=True,
        noforce=True,
        argdoc=[(
            "[HOSTS ...]", "Hosts to scan instead of the configured hosts.")])
    parser.add_option(
        "-a", "--all", "--all-suites",
        help="List all suites found on all scanned hosts (the default is "
             "just your own suites).",
        action="store_true", default=False, dest="all_suites")
    parser.add_option(
        "-n", "--name",
        metavar="PATTERN",
        help="List suites with name matching PATTERN (regular expression). "
             "Defaults to any name. Can be used multiple times.",
        action="append", dest="patterns_name", default=[])
    parser.add_option(
        "-o", "--suite-owner",
        metavar="PATTERN",
        help="List suites with owner matching PATTERN (regular expression). "
             "Defaults to just your own suites. Can be used multiple times.",
        action="append", dest="patterns_owner", default=[])
    parser.add_option(
        "--comms-timeout", metavar="SEC",
        help="Set a timeout for network connections "
             "to each running suite. The default is 5 seconds.",
        action="store", default=None, dest="comms_timeout")
    parser.add_option(
        "--poll-interval",
        help="Polling interval (time between updates) in seconds",
        type="int", metavar="SECONDS", dest="interval")
    options, args = parser.parse_args()

    if options.all_suites:
        options.patterns_owner = [r".*"]
    elif not options.patterns_owner:
        options.patterns_owner = [get_user()]
    scan_app = ScanApp(
        hosts=args,
        patterns_name=options.patterns_name,
        patterns_owner=options.patterns_owner,
        comms_timeout=options.comms_timeout,
        poll_interval=options.interval)
    try:
        gtk.main()
    except KeyboardInterrupt:
        print >> sys.stderr, "Stopping..."
        scan_app.window.destroy()
        raise SystemExit(1)


if __name__ == "__main__":
    main()
