# Copyright (C) 2020 by Animath
# SPDX-License-Identifier: GPL-3.0-or-later

from django.contrib.auth.models import User
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from rest_framework.permissions import BasePermission, IsAdminUser, IsAuthenticated, SAFE_METHODS
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet

from .serializers import BasicUserSerializer, PaymentSerializer, RegistrationSerializer
from ..models import Payment, Registration


class RegistrationViewSet(ModelViewSet):
    queryset = Registration.objects.all()
    serializer_class = RegistrationSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user', 'participantregistration__team', ]


class PaymentViewSet(ModelViewSet):
    queryset = Payment.objects.all()
    serializer_class = PaymentSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['registrations', 'grouped', 'amount', 'final', 'type', 'valid', ]


class IsTournamentOrganizer(BasePermission):
    def has_permission(self, request, view):
        reg = request.user.registration
        return request.method in SAFE_METHODS and reg.is_volunteer and reg.organized_tournaments.exists()


class VolunteersViewSet(ReadOnlyModelViewSet):
    queryset = User.objects.filter(registration__volunteerregistration__isnull=False)
    serializer_class = BasicUserSerializer
    permission_classes = [IsAdminUser | (IsAuthenticated & IsTournamentOrganizer)]
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = ['first_name', 'last_name', 'email', ]
    search_fields = ['$first_name', '$last_name', '$email', ]
