#!/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 [info] dump [OPTIONS] ARGS

Print state information (e.g. the state of each task) from a running
suite. For small suites 'watch cylc [info] dump SUITE' is an effective
non-GUI real time monitor (but see also 'cylc monitor').

For more information about a specific task, such as the current state of
its prerequisites and outputs, see 'cylc [info] show'.

Examples:
 Display the state of all running tasks, sorted by cycle point:
 % cylc [info] dump --tasks --sort SUITE | grep running

 Display the state of all tasks in a particular cycle point:
 % cylc [info] dump -t SUITE | grep 2010082406"""

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 cylc.flags
from cylc.network.suite_state import StateSummaryClient
from cylc.option_parsers import CylcOptionParser as COP
from cylc.dump import dump_to_stdout


def main():
    parser = COP(__doc__, pyro=True, noforce=True)

    parser.add_option(
        "-g", "--global", help="Global information only.",
        action="store_true", default=False, dest="global_only")

    parser.add_option(
        "-t", "--tasks", help="Task states only.",
        action="store_true", default=False, dest="tasks_only")

    parser.add_option(
        "-s", "--sort",
        help="Task states only; sort by cycle point instead of name.",
        action="store_true", default=False, dest="sort_by_cycle")

    (options, args) = parser.parse_args()
    suite = args[0]

    # default: display all information
    display_tasks = True
    display_global = True
    # check for restricted output
    if options.global_only and options.tasks_only:
        parser.error('--tasks and --global are incompatible')

    if options.global_only:
        display_tasks = False
    if options.tasks_only:
        display_global = False

    try:
        pclient = StateSummaryClient(
            suite, options.owner, options.host, options.pyro_timeout,
            options.port, options.db, my_uuid=options.set_uuid,
            print_uuid=options.print_uuid)
        # get state summary, task names, cycle points
        glbl, states, fam_states = pclient.get_suite_state_summary()
    except Exception as exc:
        if cylc.flags.debug:
            raise
        sys.exit(str(exc))

    if display_global:
        for item in glbl:
            print item, '=', glbl[item]

    if display_tasks:
        dump_to_stdout(states, options.sort_by_cycle)


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