import datetime
from typing import Set, List, Optional

from pydantic import validator

from watcher.config import settings
from watcher.logic.exceptions import ScheduleMaxDays

from .base import BaseSchema, optional, name_type, slug_type
from .staff import StaffSchema


class ScheduleGroupBaseSchema(BaseSchema):
    name: name_type
    slug: slug_type
    timeout_between_shifts: datetime.timedelta

    @validator('timeout_between_shifts')
    def check_timeout(cls, v):
        if v and v.total_seconds() % 3600:
            raise ValueError('value must be an integer number of hours')

        if v and v > datetime.timedelta(days=settings.MAX_TIMEOUT_BETWEEN_SHIFTS_DAYS):
            raise ScheduleMaxDays(message={
                'ru': f'Максимально допустимое значение - {settings.MAX_TIMEOUT_BETWEEN_SHIFTS_DAYS} дней',
                'en': f'The maximum allowed value is {settings.MAX_TIMEOUT_BETWEEN_SHIFTS_DAYS} days'
            })
        return v


class ScheduleGroupCompactSchema(ScheduleGroupBaseSchema):
    id: int
    autogenerated: bool


class ScheduleGroupListSchema(ScheduleGroupCompactSchema):
    responsibles: List[StaffSchema]
    schedules: 'List[ScheduleCompactSchema]'


# workaround of circular import
# https://stackoverflow.com/a/63425646/4227169
from watcher.api.schemas.schedule import ScheduleCompactSchema
ScheduleGroupListSchema.update_forward_refs()


class ScheduleGroupCreateSchema(ScheduleGroupBaseSchema):
    timeout_between_shifts: Optional[datetime.timedelta]


@optional
class ScheduleGroupPatchSchema(ScheduleGroupBaseSchema):
    pass


class ScheduleGroupResponsiblePutSchema(BaseSchema):
    staff: Set[int]


class ScheduleGroupSchedulesPutSchema(BaseSchema):
    schedule_ids: Set[int]
