from django.utils.translation import gettext_lazy as _

from rest_framework import serializers

from ..models import Course, LinkedCourse
from .course_module import (
    CourseModuleCreateBaseSerializer, CourseModuleDetailBaseSerializer, CourseModuleUpdateBaseSerializer,
)


class LinkedCourseDetailInlineSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = (
            'id', 'slug', 'name', 'shortname',
        )


# API
# ======

class LinkedCourseDetailSerializer(serializers.ModelSerializer):
    linked_course = LinkedCourseDetailInlineSerializer()

    class Meta:
        model = LinkedCourse
        fields = (
            'id', 'linked_course', 'name', 'description', 'estimated_time',
        )


# LabAPI
# ======

class LinkedCoursePermissionMixin(serializers.Serializer):
    def validate(self, attrs):
        request = self.context['request']

        linked_course = attrs.get('linked_course')
        if (
            linked_course and
            linked_course.author_id != request.user.id and
            not request.user.has_perm('courses.view_course', linked_course)
        ):
            raise serializers.ValidationError(_('Нет доступа к вложенному курсу'))

        return super().validate(attrs)


class LinkedCourseDetailLabSerializer(CourseModuleDetailBaseSerializer):
    linked_course = LinkedCourseDetailInlineSerializer()

    class Meta(CourseModuleDetailBaseSerializer.Meta):
        model = LinkedCourse
        fields = CourseModuleDetailBaseSerializer.Meta.fields + (
            'linked_course',
        )
        read_only_fields = fields


class LinkedCourseCreateLabSerializer(LinkedCoursePermissionMixin, CourseModuleCreateBaseSerializer):
    linked_course_id = serializers.PrimaryKeyRelatedField(
        source='linked_course', queryset=Course.objects.active(),
    )

    class Meta(CourseModuleCreateBaseSerializer.Meta):
        model = LinkedCourse
        fields = CourseModuleCreateBaseSerializer.Meta.fields + (
            'linked_course_id', 'estimated_time',
        )


class LinkedCourseUpdateLabSerializer(LinkedCoursePermissionMixin, CourseModuleUpdateBaseSerializer):
    linked_course_id = serializers.PrimaryKeyRelatedField(
        source='linked_course', queryset=Course.objects.active(), required=False,
    )

    class Meta(CourseModuleUpdateBaseSerializer.Meta):
        model = LinkedCourse
        fields = CourseModuleUpdateBaseSerializer.Meta.fields + (
            'linked_course_id', 'estimated_time',
        )
