import inspect
from django.utils.html import strip_tags
from django.utils.encoding import force_unicode

from fields import model_fields
from fields import model_meta_fields


def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models
    from django import forms

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):
        # Grab the field list from the meta class
        fields = obj._meta._fields()
        lines.append(u'')

        for field in fields:
            # Do not document AutoFields
            if type(field).__name__ == 'AutoField' and field.primary_key:
                continue

            k = type(field).__name__
            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_unicode(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_unicode(field.verbose_name).capitalize()

            lines.append(u'.. attribute::  %s' % field.name)
            lines.append(u'    ')
            # Add the field's type to the docstring
            if isinstance(field, models.ForeignKey):
                to = field.rel.to
                l = u'    %s(\':class:`~%s.%s`\')' % (type(field).__name__,
                                                   to.__module__,
                                                   to.__name__)
            elif isinstance(field, models.OneToOneField):
                to = field.rel.to
                l = u'    %s(\':class:`~%s.%s`\')' % (type(field).__name__,
                                                   to.__module__,
                                                   to.__name__)
            else:
                l = u'    %s' % type(field).__name__
            if not field.blank:
                l = l + ' (Required)'
            if hasattr(field, 'auto_now') and field.auto_now:
                l = l + ' (Automatically set when updated)'
            if hasattr(field, 'auto_now_add') and field.auto_now_add:
                l = l + ' (Automatically set when created)'
            lines.append(l)
            if help_text:
                lines.append(u'')
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u'    %s' % help_text)
            lines.append(u'    ')
            f = model_fields[type(field).__name__]
            for key in sorted(f.iterkeys()):

                if hasattr(field, key) and getattr(field, key) and getattr(field, key) != f[key] :
                    attr = getattr(field, key)
                    if key == 'error_messages':
                        error_dict = {}
                        for i in sorted(attr.iterkeys()):
                            error_dict[i] = force_unicode(attr[i])
                        attr = error_dict
                    if key == 'validators':
                        v = []
                        for i in sorted(attr):
                            n = ':class:`~%s.%s`' % (type(i).__module__,
                                                  type(i).__name__)
                            v.append(n)
                        attr = v
                    lines.append(u'    :param %s: %s' % (key, attr))
        lines.append(u'')
        lines.append(u'.. attribute:: Meta')