"""Serializer for app timetable"""
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

from establishment.models import Establishment
from timetable.models import Timetable


class ScheduleRUDSerializer(serializers.ModelSerializer):
    """Serializer for Establishment model."""
    NULLABLE_FIELDS = ['lunch_start', 'lunch_end', 'dinner_start',
                       'dinner_end', 'opening_at', 'closed_at']

    weekday_display = serializers.CharField(source='get_weekday_display',
                                            read_only=True)

    lunch_start = serializers.TimeField(required=False)
    lunch_end = serializers.TimeField(required=False)
    dinner_start = serializers.TimeField(required=False)
    dinner_end = serializers.TimeField(required=False)
    opening_at = serializers.TimeField(required=False)
    closed_at = serializers.TimeField(required=False)
    # For permission!!
    establishment_id = serializers.ReadOnlyField(source='establishment.id')

    class Meta:
        """Meta class."""
        model = Timetable
        fields = [
            'id',
            'weekday_display',
            'weekday',
            'lunch_start',
            'lunch_end',
            'dinner_start',
            'dinner_end',
            'opening_at',
            'closed_at',
            'establishment_id'
        ]

    def validate(self, attrs):
        """Override validate method"""
        establishment_pk = self.context.get('request')\
                                       .parser_context.get('view')\
                                       .kwargs.get('pk')

        establishment_slug = self.context.get('request')\
                                       .parser_context.get('view')\
                                       .kwargs.get('slug')

        search_kwargs = {'pk': establishment_pk} if establishment_pk else {'slug': establishment_slug}

        # Check if establishment exists.
        establishment_qs = Establishment.objects.filter(**search_kwargs)
        if not establishment_qs.exists():
            raise serializers.ValidationError({'detail': _('Establishment not found.')})
        attrs['establishment'] = establishment_qs.first()

        # If fields not in request data then put it in attrs with None value.
        if not self.partial:
            for field in self.NULLABLE_FIELDS:
                if field not in attrs:
                    attrs.setdefault(field, None)
        return attrs


class ScheduleCreateSerializer(ScheduleRUDSerializer):
    """Serializer for Establishment model."""
    weekday = serializers.IntegerField(write_only=True)

    class Meta:
        """Meta class."""
        model = Timetable
        fields = ScheduleRUDSerializer.Meta.fields + [
            'weekday',
        ]

    def create(self, validated_data):
        """Override create method"""
        establishment = validated_data.pop('establishment')
        weekday = validated_data.get('weekday')

        instance = super().create(validated_data)
        schedule_qs = establishment.schedule.filter(weekday=weekday)
        if schedule_qs.exists():
            schedule_qs.delete()
        establishment.schedule.add(instance)
        return instance


class TimetableSerializer(serializers.ModelSerializer):
    """Serailzier for Timetable model."""
    weekday_display = serializers.CharField(source='get_weekday_display',
                                            read_only=True)

    class Meta:
        model = Timetable
        fields = (
            'id',
            'weekday_display',
            'works_at_noon',
        )
