"""This module holds the apiv2 permissions for ``training`` app."""

from mtp.apps.accounts.apiv2.permissions import IsTrainer

class IsTrainerToEditTraineesInSession(IsTrainer):
    """Handle access to edit the session users."""

    message = "You must be the trainer of the session to perform this action."

    def has_permission(self, request, view):
        """Check if the current user has permission to edit session users.

        There are 2 permission cases:
        - Everybody can add itself in a session.
        - But only the trainer of the session can add or delete a specific trainee.

        For the parameters, see ``rest_framework.permissions.BasePermission``

        """

        is_self_registration = 'id' not in request.data or request.data['id'] == request.user.id
        is_trainer = self.is_trainer(request.user)
        is_trainer_of_the_session = is_trainer and view.session.trainer == request.user

        if request.method == 'GET':
            return True

        if request.method == 'DELETE':
            return is_trainer_of_the_session

        return is_trainer_of_the_session or is_self_registration
