from rest_framework import status
from rest_framework.exceptions import ValidationError

from api.models import EsExamPeriod
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 StudentTimetableRules(AdminApiBase):
	def post(self, request):
		try:
			self.api_log_skip_outgoing_data = True

			data = {}
			data["exam_periods"] = [
				{
					"id": exam_period.id,
					"code": exam_period.code,
					"name": exam_period.name,
					"start_date": exam_period.start_date,
					"end_date": exam_period.end_date,
					"start_time": exam_period.start_time,
					"end_time": exam_period.end_time,
				}
				for exam_period in EsExamPeriod.objects.filter(status=EsExamPeriod.STATUS_TO_CODE["active"]).order_by("name").all()
			]

			response = {
				"rules": 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)