import manimlib.imports
import inspect
import json


class ManimHelper:
    def hierarchical_phase(self, class_dict, module_list, class_name):
        if len(module_list) == 1:
            if module_list[0] not in class_dict:
                class_dict[module_list[0]] = []
            class_dict[module_list[0]].append(class_name)
        else:
            if module_list[0] not in class_dict:
                class_dict[module_list[0]] = {}
            tmp_key = module_list.pop(0)
            class_dict[tmp_key] = self.hierarchical_phase(class_dict[tmp_key], module_list, class_name)
        return class_dict

    def get_class_list(self):
        members = inspect.getmembers(manimlib.imports, inspect.isclass)
        class_dict = {}
        for (member_name, member_type) in members:
            module_list = str(member_type.__module__).split('.')
            if module_list[0] == 'manimlib':
                class_dict = self.hierarchical_phase(class_dict, module_list, member_name)
        return class_dict

    def get_arguments(self, name):
        arg_spec = inspect.getfullargspec(eval(name))
        print(arg_spec)
        arg_name = arg_spec.args
        if arg_name[0] == 'self':
            arg_name.pop(0)
        arg_default = arg_spec.defaults
        arguments = []
        for i in range(0, len(arg_name)):
            instance_dict = {'name': arg_name[i], 'default': 0}
            arguments.append(instance_dict)
        return {'arguments': arguments}

    def get_function(self, class_name):
        functions = inspect.getmembers(eval(class_name), inspect.isfunction)
        function_list = []
        for (function, _) in functions:
            if function[0:2] != '__':
                function_list.append(function)
        return {'functions': function_list}


# manim_helper = ManimHelper()
# print(manim_helper.get_function('manimlib.mobject.svg.tex_mobject.TextMobject'))
