"""Mixins for admin models."""
from django.db.models import ForeignKey


class BaseModelAdminMixin:
    """
    Class that overridden ModelAdmin and adds to readonly_fields attr
    persisted fields like created_by, modified_by.
    """

    _PERSISTENT_READ_ONLY_FIELDS = ['created_by', 'modified_by']

    def _get_fk_field_names(self, fields: iter):
        """
        Return an iterable object which contains FK model fields.
        :param fields: iterable
        :return: iterable
        """
        foreign_key_fields = []
        for field in fields:
            if isinstance(field, ForeignKey):
                foreign_key_fields.append(field.name)
        return foreign_key_fields

    def get_readonly_fields(self, request, obj=None):
        """
        Hook for specifying custom readonly fields.
        """
        _readonly_fields = list(self.readonly_fields)
        fk_field_names = self._get_fk_field_names(self.model._meta.fields)

        for field_name in fk_field_names:
            if field_name in self._PERSISTENT_READ_ONLY_FIELDS:
                _readonly_fields.append(field_name)
        return tuple(_readonly_fields)
