from datetime import timedelta

from django.contrib.auth import get_user_model

from drf_spectacular.utils import extend_schema

from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView

from baserow.api.decorators import accept_timezone
from baserow.core.models import Group, Application

from baserow_premium.admin.dashboard.handler import AdminDashboardHandler

from .serializers import AdminDashboardSerializer


User = get_user_model()


class AdminDashboardView(APIView):
    permission_classes = (IsAdminUser,)

    @extend_schema(
        tags=["Admin"],
        operation_id="admin_dashboard",
        description="Returns the new and active users for the last 24 hours, 7 days and"
        " 30 days. The `previous_` values are the values of the period before, so for "
        "example `previous_new_users_last_24_hours` are the new users that signed up "
        "from 48 to 24 hours ago. It can be used to calculate an increase or decrease "
        "in the amount of signups. A list of the new and active users for every day "
        "for the last 30 days is also included.\n\nThis is a **premium** feature.",
        responses={
            200: AdminDashboardSerializer,
            401: None,
        },
    )
    @accept_timezone()
    def get(self, request, now):
        """
        Returns the new and active users for the last 24 hours, 7 days and 30 days.
        The `previous_` values are the values of the period before, so for example
        `previous_new_users_last_24_hours` are the new users that signed up from 48
        to 24 hours ago. It can be used to calculate an increase or decrease in the
        amount of signups. A list of the new and active users for every day for the
        last 30 days is also included.
        """

        handler = AdminDashboardHandler()
        total_users = User.objects.filter(is_active=True).count()
        total_groups = Group.objects.all().count()
        total_applications = Application.objects.all().count()
        new_users = handler.get_new_user_counts(
            {
                "new_users_last_24_hours": timedelta(hours=24),
                "new_users_last_7_days": timedelta(days=7),
                "new_users_last_30_days": timedelta(days=30),
            },
            include_previous=True,
        )
        active_users = handler.get_active_user_count(
            {
                "active_users_last_24_hours": timedelta(hours=24),
                "active_users_last_7_days": timedelta(days=7),
                "active_users_last_30_days": timedelta(days=30),
            },
            include_previous=True,
        )
        new_users_per_day = handler.get_new_user_count_per_day(
            timedelta(days=30), now=now
        )
        active_users_per_day = handler.get_active_user_count_per_day(
            timedelta(days=30), now=now
        )

        serializer = AdminDashboardSerializer(
            {
                "total_users": total_users,
                "total_groups": total_groups,
                "total_applications": total_applications,
                "new_users_per_day": new_users_per_day,
                "active_users_per_day": active_users_per_day,
                **new_users,
                **active_users,
            }
        )
        return Response(serializer.data)

[(19, 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), False, 'from django.contrib.auth import get_user_model\n'), (25, 'drf_spectacular.utils.extend_schema', 'extend_schema', ([], {'tags': "['Admin']", 'operation_id': '"""admin_dashboard"""', 'description': '"""Returns the new and active users for the last 24 hours, 7 days and 30 days. The `previous_` values are the values of the period before, so for example `previous_new_users_last_24_hours` are the new users that signed up from 48 to 24 hours ago. It can be used to calculate an increase or decrease in the amount of signups. A list of the new and active users for every day for the last 30 days is also included.\n\nThis is a **premium** feature."""', 'responses': '{(200): AdminDashboardSerializer, (401): None}'}), False, 'from drf_spectacular.utils import extend_schema\n'), (39, 'baserow.api.decorators.accept_timezone', 'accept_timezone', ([], {}), False, 'from baserow.api.decorators import accept_timezone\n'), (50, 'baserow_premium.admin.dashboard.handler.AdminDashboardHandler', 'AdminDashboardHandler', ([], {}), False, 'from baserow_premium.admin.dashboard.handler import AdminDashboardHandler\n'), (88, 'rest_framework.response.Response', 'Response', (['serializer.data'], {}), False, 'from rest_framework.response import Response\n'), (71, 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), False, 'from datetime import timedelta\n'), (74, 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), False, 'from datetime import timedelta\n'), (52, 'baserow.core.models.Group.objects.all', 'Group.objects.all', ([], {}), False, 'from baserow.core.models import Group, Application\n'), (53, 'baserow.core.models.Application.objects.all', 'Application.objects.all', ([], {}), False, 'from baserow.core.models import Group, Application\n'), (56, 'datetime.timedelta', 'timedelta', ([], {'hours': '(24)'}), False, 'from datetime import timedelta\n'), (57, 'datetime.timedelta', 'timedelta', ([], {'days': '(7)'}), False, 'from datetime import timedelta\n'), (58, 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), False, 'from datetime import timedelta\n'), (64, 'datetime.timedelta', 'timedelta', ([], {'hours': '(24)'}), False, 'from datetime import timedelta\n'), (65, 'datetime.timedelta', 'timedelta', ([], {'days': '(7)'}), False, 'from datetime import timedelta\n'), (66, 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), False, 'from datetime import timedelta\n')]