import pghistory

from django.contrib.contenttypes.models import ContentType
from django.db import models
from ..querysets import ConcordiaContentTypeManager


# ---------------------------------------------------------------------------
class RecordNameContext(models.Model):
    """
    When records are deleted, it's helpful to know
    what the record represented.

    When a model doesn't have a "name" field, add
    this mixin to save the string representation
    of the model to the context.
    """

    class Meta:
        abstract = True

    def delete(self, *args, **kwargs):
        with pghistory.context(record_name=str(self)):
            return super().delete(*args, **kwargs)


# ---------------------------------------------------------------------------
class ConcordiaContentType(ContentType):
    """
    Proxy model to make it easier to add contacts via API
    RPC Methods such as changing filter password should be
    attached viewsets of this model.
    """

    IS_SYNCABLE = False

    objects = ConcordiaContentTypeManager()  # type: ignore[misc]

    class Meta:
        proxy = True
        app_label = 'concordia'

    def __str__(self) -> str:
        return self.name.title()

    @property
    def ctmodel(self) -> str:
        """For API consistency with SyncTable"""
        return str(self.model)


__all__ = (
    'RecordNameContext',
    'ConcordiaContentType',
)
