import datetime
import math

from django.conf import settings
from django.db.models import Count, Q, Prefetch
from rest_framework import status
from rest_framework.exceptions import ValidationError

from api.models import TtModule, TtActivityTemplate, TtActivity, TtWeek
from api.translation import __
from api.utils import log_critical_error, get_exception_detail
from api.validator import BaseValidator
from api.views.admin.base import AdminApiBase

class BookingList(AdminApiBase):
    def validate_request(self,request):
        rules = {
            # "academic_term_id": "required|exists:api.TtAcademicTerm,id",
            "filter": "nullable",
            "date": "nullable",
            "page": "nullable",
            "per_page": "nullable",
            "sort_by": "nullable",
            "order_by": "nullable",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get pos by id, if wrong id direct return error
        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

    def post(self, request):
        try:
            self.api_log_skip_outgoing_data=True
            self.validate_request(request)

            data = self.get_data(request)
            response = data
            return self.api_response(data=response)
        except ValidationError as e:
            first_message = e.detail['error']
            errors = e.detail['errors']
            return self.api_response(error=first_message,errors=errors,code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            e_details = get_exception_detail(e)
            log_critical_error(user_id=None,descr=e_details['descr'],url=e_details['url'],trace=e_details['trace'])
            return self.api_response(error=__("message.internal_server_error"),code=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get_data(self,request):
        host = settings.WEBSOCKET_CONFIG["HOST"]
        port = str(settings.WEBSOCKET_CONFIG["PORT"])
        endpoint = str(settings.WEBSOCKET_CONFIG["SCHEDULE_RESPONSE_ENDPOINT"])
        url = host + ":" + port + "/" + endpoint

        activities = (
            TtActivity.objects
            .filter(is_booking=1)
            .select_related("department", "week_pattern","activity_type", "zone")
            .prefetch_related(
                Prefetch("week", queryset=TtWeek.objects.order_by("start_date")),
                "week_pattern__week",
                "location",
                "location_suitability",
                "staff",
                "student_set",
                # tags means the relation add in models, __tag means the relation table tag_id get the tag object #2
            )
            .order_by(self.list_default_order_column)
        )
        target_date = request.data.get("date")

        if target_date:
            target_date_obj = datetime.datetime.strptime(target_date, "%Y-%m-%d").date()
            week = (
                TtWeek.objects
                .filter(
                    start_date__lte=target_date_obj,
                    start_date__gte=target_date_obj - datetime.timedelta(days=6),
                )
                .order_by("-start_date")
                .first()
            )
            if not week:
                # date might too early or too over, so cant get this week by date in system, no need have result
                return {
                    "total": 0,
                    "page": 1,
                    "data": [],
                }

            activities = activities.filter(
                Q(week_pattern_id__isnull=True, week__id=week.id) |
                Q(week_pattern__week__id=week.id)
            )
        activities = self.listing_filter(request, activities)

        paginated_details = self.listing_pagination(request, activities)
        total = paginated_details["total"]
        paginated_data = paginated_details["paginated_data"]
        page = paginated_details["page"]
        return_data=[]
        for val in paginated_data:
            data={}
            data["id"] = val.id
            data["code"] = val.code
            data["name"] = val.name
            data['desc'] = val.desc

            data['department'] = val.department.name if val.department else None
            data['department_id'] = val.department_id

            data['activity_type'] = val.activity_type.name if val.activity_type else None
            data['activity_type_color'] = val.activity_type.color if val.activity_type else None
            data['activity_type_id'] = val.activity_type_id
            data['zone'] = val.zone.name if val.zone else None
            data['zone_id'] = val.zone_id
            data['duration'] = val.duration
            data['slot_required'] = val.slot_required
            data['scheduled'] = True if val.scheduled else False

            data['staff_requirement_type'] = __("attr.staff_requirement_type_name."+str(val.staff_requirement_type))
            data['staff_requirement'] = val.staff_requirement
            data['location_requirement_type'] = __("attr.location_requirement_type_name."+str(val.location_requirement_type))
            data['location_requirement'] = val.location_requirement

            data['scheduled_start_time'] = val.scheduled_start_time
            data['scheduled_start_slot'] = val.scheduled_start_slot
            data['scheduled_day'] = __("attr.days_name."+str(val.scheduled_day)) if val.scheduled_day is not None else None
            data['suggested_day'] = __("attr.days_name."+str(val.suggested_day)) if val.suggested_day is not None else None
            data['suggested_time'] = val.suggested_time if val.suggested_time is not None else None
            data['suggested_time_slot'] = val.suggested_time_slot if val.suggested_time_slot is not None else None

            data['planned_size'] = val.planned_size
            data["week_pattern"] = [
                {"id": week.id, "week": week.week, "start_date": week.start_date}
                for week in val.week.all()
            ]

            data["staff"] = [
                {"id": staff.id, "name": staff.name,"code": staff.code}
                for staff in val.staff.all()
            ]

            data["location"] = [
                {"id": location.id, "name": location.name, "code": location.code}
                for location in val.location.all()
            ]
            data["location_suitability"] = [
                {"id": location_suitability.id, "name": location_suitability.name, "code": location_suitability.code}
                for location_suitability in val.location_suitability.all()
            ]

            return_data.append(data)
        return {
            "total": total,
            "page": page,
            "data": return_data,
        }