#!/usr/bin/env python

import rospy

from lama_interfaces.core_interface import core_interface
from lama_interfaces.interface_factory import interface_factory
from lama_interfaces.cleartext_interface_factory import cleartext_interface_factory
from lama_interfaces.srv import AddInterface
from lama_interfaces.srv import AddInterfaceResponse


def handle_add_interface(req):
    response = AddInterfaceResponse()
    if req.interface_type == req.SERIALIZED:
        factory = interface_factory
    else:
        factory = cleartext_interface_factory
    try:
        iface = factory(req.interface_name,
                        req.get_service_message,
                        req.set_service_message)
    except ValueError, e:
        raise rospy.ServiceException('Cannot add interface {}: {}'.format(
            req.interface_name, e))
    response.get_service_name = iface.getter_service_name
    response.set_service_name = iface.setter_service_name
    return response


if __name__ == '__main__':
    rospy.init_node('lama_interfaces', log_level=rospy.INFO)

    # Add the core interface for LamaObject and DescriptorLink objects.
    core_interface()

    # Add the server for AddInterface.
    s = rospy.Service('interface_factory', AddInterface, handle_add_interface)

    rospy.spin()
