from datetime import timedelta

from django.db.models import Manager
from drf_spectacular.utils import extend_schema
from rest_framework import generics

from .base import BaseAPIView
from .serializers import DashboardDateSerializer
from ..utils import to_edatetime, to_edate


class TranslatedListView(generics.ListAPIView, BaseAPIView):
    manager: Manager

    def get_queryset(self):
        self.update_lang()
        return self.manager.all()


@extend_schema(parameters=[DashboardDateSerializer])
class BaseDashboardIndustryView(BaseAPIView):
    serializer_class = DashboardDateSerializer

    def get_period_data(self, request, prev=False):
        serializer = self.serializer_class(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        period = serializer.validated_data['period']
        datetime = serializer.validated_data['datetime']

        given_period = to_edatetime(datetime).first_second_of_hour() if period == 'hourly' else datetime.date()
        if prev:
            prev_period = (given_period - timedelta(hours=1)) if period == 'hourly' else to_edate(given_period).yesterday()
            return period, given_period, prev_period

        return period, given_period
