"""This module holds apiv2 permissions for ``account`` app."""

from rest_framework import permissions


class IsTrainer(permissions.BasePermission):
    """Allows access only to trainers users for restricted methods."""

    RESTRICTED_METHODS = ['GET', 'DELETE', 'PATCH', 'POST', 'PUT']
    message = "You must be a trainer to perform this action."

    def has_permission(self, request, view):
        """During restricted methods, the permission is granted if the user is a trainer.

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

        Returns
        -------
        bool
            False if the user isn't a trainer during restricted methods. Else True.

        """

        if request.method in self.RESTRICTED_METHODS:
            return self.is_trainer(request.user)
        return True

    @staticmethod
    def is_trainer(user):
        """Check if the provided user is a trainer.

        Returns
        -------
        bool
            True if the user is a trainer else False.

        """

        return hasattr(user, 'is_trainer') and user.is_trainer


class IsTrainerToCreate(IsTrainer):
    """Allows access only to trainers users for creation method."""

    RESTRICTED_METHODS = ['POST']


class IsTrainerToEdit(IsTrainer):
    """Allows access only to trainers users for edition method."""

    RESTRICTED_METHODS = ['DELETE', 'PATCH', 'PUT']
