import functools


def _make_command_handler(cls):
    """
    Turn given CLS, representing a CoAP or LWM2M message, into a callable
    command.

    Since the powercmd engine uses method signature to perform tab-completion,
    we must ensure that constructor signature is retained in the wrapper.
    """

    # this decorator makes send_msg signature be a clone of cls.__init__ one
    @functools.wraps(cls.__init__)
    def send_msg(self, *args, **kwargs):
        try:
            self._send(cls(*args, **kwargs))
        except Exception as e:
            raise e.__class__('could not send %s (%s)' % (cls.__name__, e))

    return send_msg