"""Models to test the ``Lockable`` base model."""

from django.db import models

from ...models import Lockable


class StrHelper(models.Model):
    """Helper that defines a debug-readable representation of a model instance."""

    class Meta:
        abstract = True

    def __str__(self):
        """Display the Pk and, if available, the name."""

        if 'name' in self._meta.get_fields():
            return '#%s (%s)' % (self.pk, self.name)
        else:
            return '#%s' % self.pk


class BaseLockableModel(StrHelper, Lockable):
    """Base model to test ``non_lockable_fields`` with inheritance."""

    class Meta:
        abstract = True

    non_lockable_fields = ['non_lockable_field']

    # Will never be locked
    non_lockable_field = models.CharField(max_length=100)

    # Will be locked, depending of the result of ``is_field_locked`` in the subclasses.
    name = models.CharField(max_length=100)


class UnlockableM2M(StrHelper, models.Model):
    """Used for an unlockable M2M in ``LockableModel``"""

    name = models.CharField(max_length=100)


class LockableM2M(StrHelper, models.Model):
    """Used for a lockable M2M in ``LockableModel``"""

    name = models.CharField(max_length=100)


class UnlockableFK(StrHelper, models.Model):
    """Used for an unlockable FK in ``LockableModel``"""

    name = models.CharField(max_length=100)


class LockableFK(StrHelper, models.Model):
    """Used for a lockable FK in ``LockableModel``"""

    name = models.CharField(max_length=100)


class LockableModel(BaseLockableModel):
    """A lockable model to test locked and unlocked fields"""

    non_lockable_fields = ['locked', 'unlockables', 'unlockable']

    lockable = models.ForeignKey(LockableFK)
    unlockable = models.ForeignKey(UnlockableFK)

    lockables = models.ManyToManyField(LockableM2M)
    unlockables = models.ManyToManyField(UnlockableM2M)

    # Used in ``is_field_locked``, for test purpose.
    locked = models.BooleanField(default=False)

    def is_field_locked(self, field_name):
        locked = super().is_field_locked(field_name)
        if not locked:
            return False

        return self.locked
