from inspect import getfullargspec

from django.template.library import InclusionNode, parse_bits


class InclusionAdminNode(InclusionNode):
    def __init__(self, parser, token, func, template_name, takes_context=True):
        self.template_name = template_name

        params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = getfullargspec(func)
        if len(params) > 0 and params[0] == 'self':
            params = params[1:]  # ignore 'self'
        bits = token.split_contents()
        args, kwargs = parse_bits(
            parser, bits[1:], params, varargs, varkw, defaults, kwonly, kwonly_defaults, takes_context, bits[0]
        )
        super().__init__(
            func=func, takes_context=takes_context, args=args, kwargs=kwargs, filename=None
        )

    def render(self, context):
        opts = context['opts']
        app_label = opts.app_label.lower()
        object_name = opts.object_name.lower()
        self.filename = [
            'admin/%s/%s/%s' % (app_label, object_name, self.template_name),
            'admin/%s/%s' % (app_label, self.template_name),
            'admin/%s' % (self.template_name,),
        ]

        return super().render(context)
