PLUGIN_PREFIX = "robotdesigner"
OPERATOR_PREFIX = PLUGIN_PREFIX + '.'
MENU_PREFIX = "ROBOTDESIGNER_MT_"
BACKTRACE_FILTER_FUNC = ('func_wrapper', 'op_logger', '__call__')
BACKTRACE_FILTER_HIDE_CODE = ('run', 'runNestedOperator')
BACKTRACE_MESSAGE_STACK_CODE = "\t\t{0:25}\t\t({1}:{2})\n\t\t\t{3}\n"
BACKTRACE_MESSAGE_STACK = "\t\t{0:25}\t\t({1}:{2})\n"
BACKTRACE_MESSAGE_CALLSTACK = "\n\tNesting Level %d:\n\n\tCallstack:\n"
BACKTRACE_MESSAGE = "\n\tBacktrace:\n"
EXCEPTION_MESSAGE = "\tException:\t%s\n\tMessages:\n\t\t%s\n%s\n%s" class PluginManager(object):
    """
    This class handles the automatic registration of classes to Blender.
    """

    _classes_to_register = []
    _registered_classes = []
    _property_groups_to_register = []
    _registered_properties = []
    _file_plugins = []
    _bools_to_register = []
    _registered_bools = []
    PluginTypes = Enum('PluginType', 'FILE GEOMETRY SEGMENTS MODEL')

    _bl_icons_dict = None
    _icons_to_register = []
    _property_fields = {}

    @staticmethod
    def register_property_group(base=None):

        propertyTypes = (bpy.props.EnumProperty, bpy.props.StringProperty, bpy.props.BoolProperty,
                         bpy.props.StringProperty,
                         bpy.props.PointerProperty)

        def decorator(cls):
            if issubclass(cls, bpy.types.PropertyGroup):
                # RD_logger.info("Dependencies: {}".format(base))
                PluginManager._property_groups_to_register.append((cls, base))
            return cls

        return decorator



    @staticmethod
    def register_class(*args):
        """
        :term:`Class decorator<class decorator>` for :class:`.operators.RDOperator`, :class:`bpy.types.Menu`,
        :class:`bpy.types.PropertyGroup` (and more ``bpy`` classes) and :class:`.gui.CollapsibleBox`.

        An example of how to use this decorator is given in :class:`.operators.RDOperator`.

        :param args: For now, no arguments should be passed to the decorator.
        """

        def decorator(cls):
            if issubclass(cls, (RDOperator, bpy.types.Menu, bpy.types.Panel, bpy.types.Panel)):
                PluginManager._classes_to_register.append((cls, dependencies))
            elif issubclass(cls, CollapsibleBase):
                PluginManager._bools_to_register.append(cls.property_name)
            else:
                core_logger.error("Could not register %s, subclass of: {}\nDependencies: {}\n{}".format(cls, cls.mro(),
                                  dependencies, args))

                raise TypeError("Wrong with decorator")
            # print(cls)

            if not cls.__doc__:
                cls.__doc__ = "Missing documentation.\n\n"
            cls.__doc__ += "\n    **Automatically registered** to " \
                           ":class:`robot_designer_plugin.core.pluginmanager.Pluginmanager`\n"
            return cls

        if len(args) == 1 and inspect.isclass(args[0]):  # No arguments

            dependencies = []

            return decorator(args[0])
        else:  # Arguments given to decorator
            dependencies = args
            return decorator

    @classmethod
    def register_property_groups(cls, property_group, btype):
        """
        :term:`Properties<property>` have to be assigned to blender types.
        This function collects all properties and assigns them when :meth:`register` is called
        and unloads them when :meth:`unregister` is called.

        :param property_group: A class derived from :class:`bpy.types.PropertyGroup`.
        :param btype: Any type defined in :mod:`bpy.types`.
        :return:
        """
        # cls._property_groups_to_register.append((property_group, btype))

        # props = inspect.getmembers(property_group, lambda x: isinstance(x, tuple) and len(x) == 2)
        # print(props)
        # cls._property_fields[property_group]=[]
        # for name, prop in props:
        #     cls._property_fields[property_group].append((name, prop))
        #
        # for nested in inspect.getmembers(property_group, lambda x: isinstance(x, bpy.types.PropertyGroup)):
        #     cls._property_fields[property_group].append(
        #
        #     )

    @classmethod
    def register_plugin(cls, label, operators, draw_function=None, type_=PluginTypes.FILE):
        """
        .. warning::

            The plugin system is still under development.
        """
        cls._file_plugins.append((label, operators, draw_function, type_))

    @classmethod
    def get_property(cls, property):
        """
        .. warning::

            Better handling of properties is still under development.

        """
        return property[1]['attr']

    @classmethod
    def getFilePlugins(cls, type_=PluginTypes.FILE):
        """
        .. warning::

            The plugin system is still under development.
        """
        return cls._file_plugins

    @classmethod
    def register_collapsible(cls, property_name):
        """
        Called when a class of type :class:`.gui.CollapsibleBox` is created.
        """
        cls._bools_to_register.append(property_name)

    @classmethod
    def load_icon(cls, id: str, filename: str):
        '''
        :param id: ID of the label
        :param filename: Relative to :data:`.config/resource_path`
        :return: None
        '''
        file_path = os.path.join(resource_path, filename)
        if not os.path.exists(file_path):
            core_logger.debug("File does not exist: {}".format(file_path))
        else:
            cls._icons_to_register.append((id, file_path, 'IMAGE'))


    @classmethod
    def get_icon(cls, id: str):
        '''
        :param id:
        :return:
        '''

        if cls._bl_icons_dict and id in cls._bl_icons_dict:
            return cls._bl_icons_dict[id].icon_id
        else:
            return 0


    @classmethod
    def clear(cls):
        """
        When a plugin is required to be reloadable (which it should be during development) each module is imported
        twice. Therefore, this method is called before the modules are reloaded.
        """
        cls._classes_to_register.clear()
        cls._property_groups_to_register.clear()
        cls._bools_to_register.clear()
        cls._icons_to_register.clear()


    @classmethod
    def get_property(cls, obj, prop):
        '''

        :param obj:
        :param prop:
        :return:
        '''
        args, varargs, keywords, locals = inspect.getargvalues(inspect.currentframe())
        print(args, varargs, keywords, locals)


    @classmethod
    def register(cls):
        """
        Called from the top-level :func:`robot_designer_plugin.register` function in the ``__init__.py`` of the plugin.
        Registers all data collected during import.
        """
        report = ['\n']
        try:
            for class_, dependencies in cls._classes_to_register:
                bpy.utils.register_class(class_)
                report.append('\t+ class {0:35} in {1:40}'.format(class_.__name__,
                                                                  "/".join(class_.__module__.split('.')[1:])))
                cls._registered_classes.append(class_)
            core_logger.info('Done')

            core_logger.debug("Properties: {}".format(cls._property_groups_to_register))
            for prop, extends in cls._property_groups_to_register:
                report.append("\t+ property {0:33} {1:8} in {2:40}".format(prop.__name__,
                                                                          "(%s)" % extends.__name__ if extends else '',
                                                                          "/".join(prop.__module__.split('.')[1:])))

                bpy.utils.register_class(prop)
                if extends in (bpy.types.Object, bpy.types.Scene, bpy.types.Bone):
                    setattr(extends, 'RobotDesigner', bpy.props.PointerProperty(type=prop))
                cls._registered_properties.append((prop, extends))

            for i in cls._property_fields.items():
                print(i)

            for prop in cls._bools_to_register:
                setattr(bpy.types.Scene, prop, bpy.props.BoolProperty())
                cls._registered_bools.append(prop)

            if cls._icons_to_register:
                cls._bl_icons_dict = bpy.utils.previews.new()

                for icon in cls._icons_to_register:
                    report.append("\t+ icon {0:36} from {1:40}".format(icon[0], icon[1]))
                    cls._bl_icons_dict.load(*icon)
            core_logger.info("\n".join(report))

        except Exception as e:
            report.append("Error occured")
            core_logger.info("\n{}".format(report))
            core_logger.error(EXCEPTION_MESSAGE,
                              type(e).__name__, e, log_callstack(), log_callstack(back_trace=True))

        cls.clear()


    @classmethod
    def unregister(cls):
        """
        Called from the top-level :func:`robot_designer_plugin.unregister` function in the ``__init__.py`` of the
        plugin.
        Removes all data collected during import.
        """
        report = ['\n']
        try:
            for class_ in cls._registered_classes:
                bpy.utils.unregister_class(class_)
                report.append("\t- class {0:35} in {1:40}".format(class_.__name__,
                                                                  "/".join(class_.__module__.split('.')[1:])))

            for prop, extends in cls._registered_properties:
                bpy.utils.unregister_class(prop)
                if extends in (bpy.types.Object, bpy.types.Scene, bpy.types.Bone) and \
                    hasattr(extends, "RobotDesigner"):
                    delattr(extends, "RobotDesigner")

            for prop in cls._registered_bools:
                delattr(bpy.types.Scene, prop)

            core_logger.info("\n".join(report))

            if cls._bl_icons_dict:
                bpy.utils.previews.remove(cls._bl_icons_dict)

        except Exception as e:
            report.append("Error occured during clean up. You should restart blender!")
            core_logger.info("\n".join(report))
            core_logger.error(EXCEPTION_MESSAGE,
                              type(e).__name__, e, log_callstack(), log_callstack(back_trace=True))

        cls._registered_classes.clear()
        cls._property_groups_to_register.clear()
        cls._registered_bools.clear() class RDOperator(bpy.types.Operator):
    """
    Base class for the :term:`operators<operator>` in the RobotDesigner.

    :term:`Blender operators<operator>` are defined as :term:`class objects` derived from :class:`bpy.types.Operator`.
    A plugin must *register* these classes by calling :func:`bpy.utils.register_class` which causes blender to
    create a callable function *out of a method* (:meth:`bpy.types.Operator.execute`) that accepts
    :term:`keyword arguments <keyword argument>` that are bound to the class' attributes -- if they are
    subclasses
    of :class:`bpy.types.Property`. Note that the static method has not the same arguments and operates on its
    attributes.
    Finally, the operator is addressed to by its ID. For example:

    .. code-block:: python

        class NewOp(bpy.types.Operator):
            bl_label = "Description" # Obligatory
            bl_idname = "plugin_name.newop" # obligatory

            test = StringProperty() # A property. It's value is passed when calling the operator.

            def execute(self, context):
                self.report({INFO}, self.text)
                return {'FINISHED'}

        # ...

        bpy.utils.register(NewOp)

        # ...

        bpy.ops.plugin_name.newop(test="Hello World)


    This example show an operator that opens a window containing the message *"Hello World"*. While this is feasible
    for smaller plugins, what happens, if you have a lot of operators written, and you want to have code completion.
    What happens if you want to refactor the names of of the identifier or class attributes. While for the latter there
    is no simple solution available, the :mod:`robot_designer_plugin.core` provides this wrapper class with
    an additional ``run(**kwargs)`` method (that can---and should---be overridden to provide keyword completion).
    Furthermore, it provides decorators for automatically setting preconditions (that define the
    :meth:`bpy.types.Operator.poll` method) for automatic condition checking, logging functionality and post condition
    checking. Together with the :meth:`.pluginmanager.PluginManager.register` method, this makes developing faster (
    code completion,
    code navigation, less verbosity, ...) and safer.

    An examplary :term:`operator` looks like this:

    .. literalinclude:: ../../../resources/templates/operator.py
        :emphasize-lines: 7-11,16-18, 31-33, 60-62
        :lines: 50-111
        :linenos:

    A template is located in ``<RobotDesignerDirectory>/resources/templates/operator.py`` (where you should insert
    the path to the repository) that can be used to quickly write new operators.
    """

    _pre_conditions = {}
    """Dictionary set by the :meth:`PreConditions` decorator. Stores the :class:`.conditions.Condition` that are
    checked for each :class:`RDOperator` -based operator"""

    logger = logger
    """For convenience, every the operators share a logging instance."""

    @classmethod
    def poll(cls, context):
        """
        The :meth:`bpy.types.Operator.poll` class method is called every time, an operator is to be executed, but
        also when it is placed in a guy (it becomes greyed out). This method is defined in this base class and
        the checks are defined by a list of :class:`.conditions.Condition` derived classes that are given by
        the :meth:`Preconditions` decorator. Derived classes do not need to override this method and should
        call the parent's method otherwise.

        :param context: The actual Blender :term:`context`.
        :type context: :class:`bpy.types.Context`
        :return:
        """
        if cls in cls._pre_conditions:
            check, messages = Condition.check_conditions(*cls._pre_conditions[cls])
            if not check:
                cls.logger.debug("Unmet preconditions: \n{}".format(messages))
            return check
        return True

    @staticmethod
    def pass_keywords():
        """
        Helper function that extracts the arguments of the callee (must be a (class) method) and returns them.

        Credits to `Kelly Yancey <http://kbyanc.blogspot.de/2007/07/python-aggregating-function-arguments.html>`_
        """

        args, _, _, locals = inspect.getargvalues(inspect.stack()[1][0])
        args.pop(0)
        kwargs = {i: j for i, j in locals.items() if i in args}
        return kwargs

    @classmethod
    def run(cls, **kwargs):
        """
        Enables to run an :ref:`operator` by calling its class object.
        Child classes *should* override this method with keywords. Then your :term:`IDE` will be able to assist you
        The :meth:`pass_keywords` function makes
        overriding very convenient (just copy the method's body):

        .. code: python

            class NewOp(RDOperator):
                model_name = StringProperty(name="Enter model name:")
                base_segment_name = StringProperty(name="Enter root segment name:", default="")

                @classmethod
                def run(cls, model_name, base_segment_name):
                    return super().run(**cls.pass_keywords())

        .. warning:

            :term: `refactoring<Refactoring>` class attributes (i.e., the keywords) requires you modify both the
            overridden run function *and* your attributes.

        In addition, this method also does extensive error and exception handling writing everything to the log file
        (see :mod:`.logfile`).

        :param kwargs: The keyword arguments passed to the :ref:`Operator` (**must** match the names of the class's
            attributes (only of type :class:`bpy.types.Property).
        :return: The return values of :meth:`bpy.types.Operator.execute`.
        """
        try:
            # cls.logger.debug('get registered operator')
            return get_registered_operator(cls)(**kwargs)


        except TypeError as e:
            bad_kwargs = []
            for kwarg in kwargs.keys():
                if kwarg not in dir(cls):
                    bad_kwargs.append(kwarg)

            cls.logger.error('Exception when running operator {} ({}):'
                             '\n\tkeywords:\t%s\n\tBad keywords:\t{}'
                             '\n\tException:\t%s\n\tMessages:\n\t\t{}'.format(
                             cls.bl_idname, cls.__name__,
                             kwargs,
                             ', '.join(bad_kwargs), type(e).__name__,
                             '\n\t\t'.join(e.__str__().split('\n'))))
            InfoBox.global_messages.append(e.__str__())
            raise e

            # todo check for keyword arguments without default value

        except RuntimeError as e:
            cls.logger.error('Exception when running operator {} ({}):'
                             '\n\tException:\t{}\n\t{}\n'.format(cls.bl_idname, cls.__name__,
                             type(e).__name__, '\n\t'.join(e.__str__().split('\n'))))
            check, messages = Condition.check_conditions(*cls._pre_conditions[cls])
            cls.logger.info("Conditions set for this operator: {}\n\t{}\n\t{}".format(cls._pre_conditions[cls], check,
                            messages))
            InfoBox.global_messages.append(e.__str__())
            raise e
        except Exception as e:
            cls.logger.error('THIS CODE SHOULD NEVER BE EXECUTED: {}\n{}\n'.format(e, log_callstack(back_trace=True)))
            InfoBox.global_messages.append(e.__str__())
            raise e

    @classmethod
    def place_button(cls, layout, text=None, infoBox=None, **kwargs):
        """
        This is a convenience method that let's the developer create a button executing the operator from the gui.
        The results of the :meth:`poll` method (i.e., checking it's conditions) can be optionally passed to an
        :class:`.gui.InfoBox` instance such that a report for a group of operators can be displayed (i.e., why
        it is not executable)

        :param layout: the gui element to place the button (see :meth:`bpy.types.Panel.draw`)
        :param text: Optionally override the text in the ``bl_label`` attribute.
        :param infoBox: Optional instance of :class:`.gui.InfoBox`
        :param kwargs: Additional keyword arguments to :meth:`bpy.types.UILayout.operator`)
        :return: The operator instance (this can be used to set one of the class's attributes)
        """
        if infoBox and cls in cls._pre_conditions:
            # if not isinstance(infoBox, InfoBox):
            #    raise TypeError("Argument: infobox must be of type %s (not %s)" % (InfoBox.__name__, type(infoBox)))

            check, messages = Condition.check_conditions(*cls._pre_conditions[cls])
            if not check:
                infoBox.add_message(messages)

        # Checkconditions
        # todo check KWargs
        if not text:
            text = cls.bl_label
        return layout.operator(cls.bl_idname, text=text, **kwargs)

    @staticmethod
    def OperatorLogger(func):
        """
        Decorator for the `bpy.types.Operator.execute` method (only for sub classes of :class:`RDOperator`).

        Performs logging and exception handling.
        """

        def op_logger(self, context):

            # `callargs['self']` parameter refers to the operator instance
            # This is done in order to avoid positional arguments.
            # That way, the decorator can be used as @OperationLogger instead of
            # @OperationLogger
            # callargs = inspect.getcallargs(func,*args)

            class_name = self.__class__.__name__
            id = self.__class__.bl_idname

            # Execute the Operator
            try:
                # self.logger.debug("Entering {}() from {}({}):\n{}".format(
                #                    func.__name__, id, class_name,
                #                    log_callstack()))

                result = func(self, context)
                # self.logger.debug("Leaving {}() {}({})".format(id, class_name, result))

                return result

            except Exception as e:
                InfoBox.global_messages.append(
                    "%s: %s (%s)" % (type(e).__name__, e.__str__(), log_callstack_last(back_trace=True)))
                message = "Operator %s (%s) threw an exception:%s\n\t%s" % (id, class_name,
                                                                            type(e).__name__, e)
                self.logger.error("Operator {} ({}) threw an exception:\n {} {} {} {}".format(EXCEPTION_MESSAGE,
                                  id, class_name, type(e).__name__, e, log_callstack(), log_callstack(back_trace=True)))
                if isinstance(self, RDOperator):
                    self.report({'ERROR'}, message)
                    return {'FINISHED'}
                else:
                    # Menu has no report and must return None
                    return

        return op_logger

    @staticmethod
    def Preconditions(*conditions):
        """
        :term:`Class decorator<class decorator>` for :term:`operators<operator>`.

        Registers the conditions (of type :class:`.conditions.Condition`) for its subclasses. They will be
        checked within the :meth:`poll` and :meth:`place_button` methods.

        :param conditions: a number of subclasses of :class:`.conditions.Condition`.
        """

        def decorator(cls: RDOperator):  # Todo check why this check fails some times
            if not issubclass(cls, RDOperator):
                raise TypeError("Preconditions: Can only decorate sub classes of RDOperator.i \n%s \n%s \n%s\n%s" % (
                    cls.__name__,
                    cls.mro(), type(cls), conditions))

            cls._pre_conditions[cls] = conditions

            cls.__doc__ += "\n    **Preconditions**:\n\n%s" % "".join(
                '    * :class:`%s.%s`\n' % (i.__module__, i.__name__) for i in conditions)

            # RDOperator.logger.debug("Decorating {}, \nArgs: {}\n {}, {}, {}".format(cls, args, issubclass(cls, RDOperator),
            #                        issubclass(cls, bpy.types.Operator), [RDOperator is i for i in cls.mro()]))
            # for i in cls.mro():
            #    print(i)
            return cls

        # RDOperator.logger.debug("Precondition:\nArgs: {}".format(args))
        if len(conditions) == 1 and issubclass(conditions[0], RDOperator):
            raise TypeError('Decorator Preconditions must be called with arguments of subclasses of Condition')
        else:
            if any([issubclass(i, RDOperator) for i in conditions]):
                raise TypeError('Decorator Preconditions must be called with arguments of subclasses of Condition '
                            '%s', conditions)

            return decorator


    @staticmethod
    def Postconditions(*conditions):
        """
        Method decorator for the :meth:`bpy.types.Operator.execute` method. Works only with :term:`operators<operator>`
        derived :class:`RDOperator`.

        Checks whether post conditions are met after calling the operator. Reports an error message to the log file
        (see :mod:`.logfile`)

        :param conditions: a number of subclasses of :class:`.conditions.Condition`.
        """

        def decorator(func):
            def func_wrapper(self, context):
                result = func(self, context)
                check, messages = Condition.check_conditions(*conditions)
                if not check:
                    self.report({'ERROR'}, messages)
                    logger.error('Postcondition not met: %s\\n%s\n%s', messages, log_callstack(), log_callstack(True))
                    InfoBox.global_messages.append(messages)
                return result

            doc = "\n    **Postconditions**:\n\n%s" % "".join(
                '    * :class:`%s.%s`\n' % (i.__module__, i.__name__) for i in conditions)
            func.__doc__ = func.__doc__ + doc if func.__doc__ else doc
            return func_wrapper

        return decorator class ModelSelected(Condition):
    @staticmethod
    def check():
        """
        :ref:`condition` that assures the armature is selected.

        :return: True if the condition is met, else false. String with error message.
        """
        if bpy.context.active_object:
            return (
                bpy.context.active_object.type == "ARMATURE",
                "Model not selected and active.",
            )
        else:
            return False, "No model selected" class SingleMeshSelected(Condition):
    @staticmethod
    def check():
        """
        :ref:`condition` that assures that a single mesh object (i.e., two selected objects where exactly one is a mesh).

        :return: True if the condition is met, else false. String with error message.
        """
        selected = [i for i in bpy.context.selected_objects if i.type == "MESH"]
        return len(selected) == 1, "Single mesh object must be selected." class SingleSegmentSelected(Condition):
    @staticmethod
    def check():
        """
        :ref:`condition` that assures that a single mesh object (i.e., two selected objects where exactly one is a mesh).

        :return: True if the condition is met, else false. String with error message.
        """
        if bpy.context.active_bone:
            selected_segments = [
                i for i in bpy.context.active_object.data.bones if i.select
            ]
            return len(selected_segments) == 1, "Single Segment must be selected"
        else:
            return False, "No Object Selected" class RDSelectedObjects(PropertyGroupHandlerBase):
class RDGlobals(PropertyGroupHandlerBase):
    def __init__(self):
    def debug_level_callback(self, context):
    def updateGlobals(self, context):
    def updateBoneName(self, context):
    def display_physics(self, context):
    def attach_world(self, context):
    def updateMuscleName(self, context):
    def update_geometry_name(self, context):
    def update_wrapping_name(self, context):
    def display_geometries(self, context):
    def display_wrapping_geometries(self, context):
    def display_muscles(self, context):
    def display_sensors(self, context):
    def name_update(self, context):
    def muscle_dim_update(self, context):
    def __init__(self): def LogFunction(func):
    def func_logger(self, context):
def log_callstack(back_trace=False):
def log_callstack_last(back_trace=False): class SelectModel(RDOperator):
    """
    :ref:`operator` for ...

    **Preconditions:**

    **RDOperator.Postconditions:**
    """

    bl_idname = config.OPERATOR_PREFIX + "selectarmature"
    bl_label = "Select Model"

    model_name: StringProperty()

    @classmethod
    def run(cls, model_name=""):
        return super().run(**cls.pass_keywords())

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected)
    def execute(self, context):
        from . import segments

        for obj in context.scene.objects:
            obj.select_set(False)

        context.view_layer.objects.active = bpy.data.objects[self.model_name]
        context.active_object.select_set(True)
        global_properties.model_name.set(context.scene, self.model_name)
        global_properties.old_name.set(context.scene, self.model_name)
        # not so sure if this is needed at all

        if len(context.active_object.data.bones) > 0:
            baseBoneName = context.active_object.data.bones[0].name
            segments.SelectSegment.run(segment_name=baseBoneName)
        return {"FINISHED"} class SelectWrappingObject(RDOperator):
    """
    :ref:`Operator <operator>` for selecting a wrapping object (:class:`bpy.types.Object` with `bpy.types.Mesh` data)
    second to the selected model (Blender object with :class:`bpy.types.Armature` data)
    """

    bl_idname = config.OPERATOR_PREFIX + "select_wrappingobject"
    bl_label = "Select Wrapping Object"

    wrapping_name: StringProperty()

    @classmethod
    def run(cls, wrapping_name=""):
        return super().run(**cls.pass_keywords())

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected, SingleMeshSelected)
    def execute(self, context):
        mesh = bpy.data.objects[self.wrapping_name]

        if mesh.type != "MESH" or mesh.RobotDesigner.tag != "WRAPPING":
            self.report({"ERROR"}, "Object is no wrapping geometry (Mesh). Is %s" % mesh.type)
            global_properties.wrapping_name.set(context.scene, "Search")
            return {"FINISHED"}

        # Has the side effect of de-selecting all other objects except for the armature and our mesh.
        global_properties.wrapping_name.set(context.scene, self.wrapping_name)

        #    context.region.tag_redraw()
        #    context.area.tag_redraw()
        return {"FINISHED"}
import bpy
from bpy.props import StringProperty, BoolProperty
from mathutils import Vector, Matrix, Euler
from math import pi
from ..core import config, PluginManager, RDOperator
from .helpers import ModelSelected, SingleMeshSelected, SingleSegmentSelected
from ..properties.globals import global_properties
from ..core.logfile import operator_logger
from .model import SelectModel
from .rigid_bodies import SelectWrappingObject
        from .model import SelectModel
        from .segments import SelectSegment
        from . import segments, model
        from .model import SelectModel
        from .rigid_bodies import SelectGeometry, AssignGeometry
        from .segments import SelectSegment
        from .model import SelectModel
        from .rigid_bodies import SelectGeometry, AssignGeometry
        from .segments import SelectSegment
#     @RDOperator.OperatorLogger
#     def execute(self, context):
#
#         model = bpy.data.objects[global_properties.model_name.get(context.scene)]
#         active_muscle = bpy.data.objects[
#             global_properties.active_muscle.get(bpy.context.scene)
#         ]
#
#         wrapping_object = context.scene.objects[self.wrapping_name]
#         wrapping_object.RobotDesigner.wrap.muscleNames.add()
#         nr = len(wrapping_object.RobotDesigner.wrap.muscleNames)
#         wrapping_object.RobotDesigner.wrap.muscleNames[nr - 1].name = active_muscle.name
#
#         wrapList = active_muscle.RobotDesigner.muscles.connectedWraps
#         wrapList.add()
#         nrw = len(wrapList)
#         wrapList[nrw - 1].wrappingName = self.wrapping_name
#
#         return {"FINISHED"}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)

    @classmethod
    def run(cls, wrapping_name=""):
        return super().run(**cls.pass_keywords())


# operator to select mesh
@RDOperator.Preconditions(ModelSelected, SingleSegmentSelected)
@PluginManager.register_class
class GenerateMeshFromSegment(RDOperator):
    """
    :ref:`operator` for generating a mesh from the given segment.

    """

    bl_idname = config.OPERATOR_PREFIX + "generate_mesh"
    bl_label = "Generate Geometry for Segment"

    @RDOperator.OperatorLogger
    @RDOperator.Postconditions(ModelSelected, SingleSegmentSelected)
    def execute(self, context):


        C = bpy.context
        D = bpy.data

        model = C.active_object

        bone_name = C.active_bone.name
        pose_bone = C.active_object.pose.bones[bone_name]

        if not C.active_bone.parent:
            self.report({"ERROR"}, "Does not work for root segments")
            return {"CANCELLED"}

        parent_bone = C.active_object.pose.bones[C.active_bone.parent.name]
        parent_name = parent_bone.name

        parent_frame = model.matrix_world @ parent_bone.matrix

        bone_world = model.matrix_world @ pose_bone.matrix
        bone_to_parent = bone_world.inverted() @ parent_frame
        parent_to_bone = parent_frame.inverted() @ bone_world
        l = bone_to_parent.translation.length

        v1 = bone_to_parent.translation
        max_v1 = max(abs(i) for i in v1)
        v2 = parent_to_bone.translation
        max_v2 = max(abs(i) for i in v2)

        if max_v1 != 0:
            bpy.ops.curve.primitive_bezier_circle_add(radius=l / 20)
            operator_logger.debug(l)

            bevel = C.active_object

            bezier = bpy.ops.curve.primitive_bezier_curve_add()

            bezier = C.active_object
            bezier.data.bevel_object = bevel

            bezier.matrix_world = bone_world

            operator_logger.debug(bezier.matrix_world)

            bpy.ops.object.mode_set(mode="EDIT", toggle=False)

            a = bezier.data.splines[0].bezier_points[0]
            b = bezier.data.splines[0].bezier_points[1]

            a.co = (0, 0, 0)
            b.co = bone_to_parent.translation

            operator_logger.debug(v1, max_v1)
            v1 = Vector([0.1 * i / max_v1 if abs(i) == max_v1 else 0.0 for i in v1])

            v2 = Vector([0.1 * i / max_v2 if abs(i) == max_v2 else 0.0 for i in v2])

            a.handle_right = v1
            a.handle_left = -1 * v1
            operator_logger.debug(v1, a.handle_right, a.handle_left)

            m = Matrix()
            m.translation = v2

            operator_logger.debug(m, bone_to_parent.inverted() @ parent_frame @ m)
            b.handle_left = (bone_to_parent @ m).translation
            m.translation = -1 * v2

            b.handle_right = (bone_to_parent @ m).translation
            operator_logger.debug(v2, b.handle_right, b.handle_left)

            bpy.ops.object.mode_set(mode="OBJECT", toggle=False)
            bpy.ops.object.convert(target="MESH")
            bpy.ops.object.select_all(action="DESELECT")
            bevel.select_set(True)
            bpy.ops.object.delete()


            SelectModel.run(model_name=model.name)