"""This module holds mixins for the ``api`` app."""

from rest_framework import status
from rest_framework.decorators import list_route
from rest_framework.mixins import DestroyModelMixin
from rest_framework.response import Response

from mtp.apps.sync.models import Syncable


class SoftDestroyModelMixin(DestroyModelMixin):
    """Override ``DestroyModelMixin`` to handle soft-deletion of ``Syncable`` instance."""

    def perform_destroy(self, instance):
        """Soft-delete ``Syncable`` instances and perform destroy others instances.

        For the parameters, see ``rest_framework.mixins.DestroyModelMixin``"""

        if isinstance(instance, Syncable):
            instance.remove()
        else:
            super().perform_destroy(instance)


class OrderableListMixin:
    """Mixin that saves the orders

    Your model should inherit from ``orderable.models.Orderable``.
    And you should use ``mtp.apps.api.routers.SimpleRouterWithNesting`` or
    ``rest_framework_extensions.routers.SimpleRouter``

    ``list_route`` decorator doesn't work with
    ``rest_framework_extensions.routers.ExtendedDefaultRouter``

    """

    @list_route(methods=['post'])
    def order(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """Endpoint to order photos.

        Parameters
        ----------
        For the parameters, see the ``viewsets.ModelViewSet`` class.

        Returns
        -------
        Response

        """

        order = 1
        for object_id in request.data.getlist('order'):
            obj = self.get_queryset().get(pk=object_id)
            obj.sort_order = order
            obj.save()
            order += 1

        return Response(status=status.HTTP_200_OK)
