#! /usr/bin/env python

"""
usage: %prog [args]
"""

import rospkg

import os
import sys
import string
from argparse import ArgumentParser
import subprocess

import app_manager
import rospy

def main():
    rospy.init_node('app_manager')

    argv = rospy.myargv()
    parser = ArgumentParser()

    parser.add_argument("--applist", default=None, nargs="*",
                        help="path to applist directories", metavar="PATH")
    args = parser.parse_args(argv[1:])

    applist = []
    if args.applist is not None:
        rospy.loginfo("Loading applist from --applist option")
        for path in args.applist:
            if not os.path.exists(path):
                parser.error("applist directory [%s] does not exist.\nUse --applist to set the correct location" % (path))
        applist = args.applist
    else:
        rospy.loginfo("Loading from plugin definitions")
        try:
            out = subprocess.check_output(["rospack", "plugins", "--attrib=app_dir", "app_manager"]).strip()
            if not out:
                parser.error("No app directory found")
            lines = out.split(os.linesep)
            for line in lines:
                pkg, app_dir = line.strip().split()
                if not os.path.exists(app_dir):
                    parser.error("In package '%s', app_dir '%s' does not exist. Maybe forgot to start with ${prefix}?" % (pkg, app_dir))
                applist.append(app_dir)
        except subprocess.CalledProcessError:
            parser.error("--applist option is not specified, but loading from plugin definition failed.")

    robot_name = rospy.get_param('/robot/name', 'robot')
    robot_type = rospy.get_param("/robot/type", None)
    if robot_type is None:
        rospy.loginfo("The param '/robot/type' is undefined. Using apps for any platforms")
    else:
        rospy.loginfo("Using apps for platform '%s'" % robot_type)

    interface_master = rospy.get_param('~interface_master', 'http://localhost:11312')

    try:
        app_list = app_manager.AppList(applist, platform=robot_type)
    except app_manager.AppException as e:
        print >> sys.stderr, "Failed to load app list: %s"%(str(e))
        sys.exit(1)

    exchange = None

    exchange_url = rospy.get_param('/robot/exchange_url', '')
    if (exchange_url != ""):
        try:
            app_path = os.path.join(rospkg.get_ros_home(), "exchange")
            if (not os.path.exists(app_path)):
                os.makedirs(app_path)
            exchange = app_manager.Exchange(exchange_url, app_path, lambda(x): rospy.logerr(x))
            app_list.add_directory(os.path.join(app_path, "installed"))
        except app_manager.AppException as e:
            print >> sys.stderr, "Failed to load exchange: %s"%(str(e))
            sys.exit(1)

    am = app_manager.AppManager(robot_name, interface_master, app_list, exchange)

    rospy.on_shutdown(am.shutdown)

    rospy.spin()



if __name__ == "__main__":
    main()
