# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import


from django.core.management.base import BaseCommand
import types


class Command(BaseCommand):

    def handle(self, *args, **options):
        from rpc.api_control import MethodInfo, ListInterfaceDescriptor
        from rpc.instance import api_manager
        method_name_list = sorted(api_manager.get_method_list())
        method_info_list = [api_manager.get_method_info(method_name) for method_name in method_name_list]
        for method_info in method_info_list:
            assert isinstance(method_info, MethodInfo)
            list_interface_descriptor = method_info.list_interface_descriptor
            if not list_interface_descriptor:
                continue
            assert isinstance(list_interface_descriptor, ListInterfaceDescriptor)
            print(
                '{:39s} {:19s} {:19s} {:19s} {:39s} {:s}'.format(
                    method_info.name,
                    list_interface_descriptor.offset_name or '-',
                    list_interface_descriptor.limit_name or '-',

                    list_interface_descriptor.element_model.__name__
                    if list_interface_descriptor.element_model
                    else '-',

                    list_interface_descriptor.element_model.__module__
                    if list_interface_descriptor.element_model
                    else '-',

                    ' '.join([
                        self.format_func(f)
                        for f
                        in list_interface_descriptor.element_func_list
                    ]),
                )
            )

    @classmethod
    def format_class(cls, klass):
        return '{}.{}'.format(klass.__module__, klass.__name__)

    @classmethod
    def format_func(cls, func):
        if isinstance(func, types.FunctionType):
            return '{}.{}'.format(func.__module__, func.__name__)
        if isinstance(func, types.UnboundMethodType):
            return '{}.{}'.format(cls.format_class(func.im_class), func.im_func.func_name)
        if isinstance(func, property):
            return '{}'.format(cls.format_func(func.fget))
        return repr(func)


