import logging
from uuid import UUID

from django.conf import settings
from django.db.models import Model
from django.utils.module_loading import import_string

from .fields import UUID6Field
from .mixins import (
    FilterFields,
    ManageTenantFields,
    NamesUrlsMixin,
    ValidateConstraints,
)

try:
    field_docs = import_string(settings.FIELD_DOCS_PATH)
except ImportError:
    field_docs = object

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
class BaseIntegerPKModel(
    FilterFields,
    ValidateConstraints,
    ManageTenantFields,
    NamesUrlsMixin,
    Model,
):
    """
    Consoles that don't override the mixin classes of this model
    can use it directly.
    """

    class Meta:
        abstract = True


# ---------------------------------------------------------------------------
class UUIDModelMixin(ValidateConstraints, Model):
    id = UUID6Field(primary_key=True, serialize=False, editable=False)

    class Meta:
        abstract = True

    @property
    def row_pk(self):
        """DataTables helper attribute"""
        return f'row_{self.pk.hex}'

    def cast_pk(self, value):
        """Cast value to UUID for use as primary key"""
        try:
            return UUID(value)
        except AttributeError:
            return value


# ---------------------------------------------------------------------------
class BaseUUIDPKModel(FilterFields, ManageTenantFields, NamesUrlsMixin, UUIDModelMixin, Model):
    """
    Consoles that don't override the mixin classes of this model
    can use it directly.
    """

    class Meta:
        abstract = True


__all__ = (
    'field_docs',
    'BaseIntegerPKModel',
    'BaseUUIDPKModel',
    'NamesUrlsMixin',
    'UUIDModelMixin',
    # for convenience imports
    'UUID6Field',
)
