#!/usr/bin/env python
# Copyright (c) 2018, Clearpath Robotics, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the Willow Garage, Inc. nor the names of its
#       contributors may be used to endorse or promote products derived from
#       this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Support controller groups so it is easy to spawn a set controllers and also switch
# to any other group at run time.
#
# Author: Yong Li
#
from __future__ import print_function
import rospy
from argparse import ArgumentParser
from controller_manager import controller_manager_interface
from controller_manager_msgs.srv import ListControllers, ListControllersRequest


def _read_group(group):
    ''''
    Return 2 sets of controllers. The first set includes controllers required for the given group,
    and the second set includes the controllers that should be stopped if the given group is chosen.
    '''
    groups = rospy.get_param('controller_groups', {})
    desired_controllers = set(groups.get(group, ()))
    if not desired_controllers:
        rospy.logerr('There is no controller defined in group {}'.format(group))
        return None, None
    # Remove duplicates.
    all_controllers = set()
    for controllers in groups.values():
        all_controllers.update(controllers)
    return desired_controllers, all_controllers - desired_controllers


def _get_loaded_controllers():
    rospy.wait_for_service('controller_manager/list_controllers', timeout=5)
    s = rospy.ServiceProxy('controller_manager/list_controllers', ListControllers)
    resp = s(ListControllersRequest())
    controllers = {}
    for controller in resp.controller:
        controllers[controller.name] = controller.state == 'running'
        if controller.state not in ('running', 'stopped'):
            rospy.logerr('Unknown controller state {}'.format(controller.state))
    return controllers


def _list_group(args):
    groups = rospy.get_param('controller_groups', {})
    print('Number of groups: {}'.format(len(groups)))
    for group, controllers in sorted(groups.items()):
        print('  {}'.format(group))
        for controller in controllers:
            print('      {}'.format(controller))


def _spawn_group(args):
    desired_controllers, _ = _read_group(args.group)
    if not desired_controllers:
        return
    for controller in desired_controllers:
        controller_manager_interface.load_controller(controller)
    for controller in desired_controllers:
        controller_manager_interface.start_controller(controller)


def _switch_group(args):
    desired_controllers, other_controllers = _read_group(args.group)
    if not desired_controllers:
        return
    loaded_controllers = _get_loaded_controllers()

    # Stop running controllers that we no longer need.
    to_stop = []
    for controller in other_controllers:
        if loaded_controllers.get(controller, False):
            to_stop.append(controller)

    # Load and start every desired controller if needed.
    to_start = []
    for controller in desired_controllers:
        if controller not in loaded_controllers:
            if not controller_manager_interface.load_controller(controller):
                # load_controller() already prints an error.
                print('Cancel group switching')
                return
        if not loaded_controllers.get(controller, False):
            to_start.append(controller)

    controller_manager_interface.start_stop_controllers(start_controllers=to_start, stop_controllers=to_stop)


def _main():
    parser = ArgumentParser(description='Controller Group Utility')
    subparsers = parser.add_subparsers(title='Commands', metavar='')

    list_parser = subparsers.add_parser('list', help='list available groups')
    list_parser.set_defaults(func=_list_group)

    spawn_parser = subparsers.add_parser(
        'spawn', help='load all controllers in all groups and start controllers in the specified group')
    spawn_parser.add_argument('group', help='name of the group to start')
    spawn_parser.set_defaults(func=_spawn_group)

    switch_parser = subparsers.add_parser('switch', help='switch to the specified group')
    switch_parser.add_argument('group', help='name of the group to switch to')
    switch_parser.set_defaults(func=_switch_group)

    args = parser.parse_args(rospy.myargv()[1:])
    args.func(args)


if __name__ == '__main__':
    _main()
