from rest_framework import serializers
from webapp.models import *


class SignupSerializer(serializers.ModelSerializer):
    signupForm_id = serializers.PrimaryKeyRelatedField(
        source="signupForm", queryset=SignupForm.objects.all()
    )
    list_name = serializers.CharField(read_only=True)
    submit_id = serializers.UUIDField(required=False)

    def add_extra_fields(self, validated_data):
        questions = validated_data["signupForm"].questions
        name_ids = list(filter(lambda x: x["type"] == "name", questions))
        email_ids = list(filter(lambda x: x["type"] == "email", questions))

        # Send email to first email field in the form
        if len(email_ids) > 0:
            id = email_ids[0]["id"]
            email_value = validated_data["answer"].get(id)
            validated_data["email"] = email_value
        # Combine all name fields to list_name
        if len(name_ids) > 0:
            # name_value = validated_data["answer"].get(name_fields[0]["id"], None)
            all_names = map(lambda x: validated_data["answer"].get(x["id"]), name_ids)
            validated_data["list_name"] = " ".join(all_names)

    def create(self, validated_data):
        self.add_extra_fields(validated_data)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        self.add_extra_fields(validated_data)
        return super().update(instance, validated_data)

    class Meta:
        model = Signup
        fields = ("id", "submit_id", "signupForm_id", "answer", "list_name")
        extra_kwargs = {
            "url": {
                "view_name": "signup-detail",
            }
        }


class SignupFormSerializer(serializers.ModelSerializer):
    signups = serializers.SlugRelatedField(
        slug_field="list_name",
        many=True,
        read_only=True,
        required=False,
    )

    class Meta:
        model = SignupForm
        fields = (
            "id",
            "title_fi",
            "title_en",
            "visible",
            "isOpen",
            "start_time",
            "end_time",
            "email_content",
            "questions",
            "schema",
            "signups",
            "quota",
        )


class EventSerializer(serializers.ModelSerializer):
    signupForm = SignupFormSerializer(
        source="filtered_signup_forms",
        many=True,
        read_only=True,
    )

    signup_id = serializers.PrimaryKeyRelatedField(
        queryset=SignupForm.objects.all(),
        many=True,
        write_only=True,
    )
    tag_id = serializers.PrimaryKeyRelatedField(
        queryset=Tag.objects.all(),
        many=True,
        write_only=True,
    )

    class Meta:
        model = Event
        fields = (
            "id",
            "tag_id",
            "tags",
            "visible",
            "image",
            "title_fi",
            "title_en",
            "description_fi",
            "description_en",
            "content_fi",
            "content_en",
            "start_time",
            "end_time",
            "location_fi",
            "location_en",
            "signup_id",
            "signupForm",
        )
        read_only_fields = ["tags", "signupForm"]
        depth = 1

    def create(self, validated_data):
        signupForms = validated_data.pop("signup_id", [])
        tags = validated_data.pop("tag_id")
        event = Event.objects.create(**validated_data)
        for form in signupForms:
            event.signupForm.add(form)
        for tag in tags:
            event.tags.add(tag)
        event.save()
        return event

    def update(self, instance, validated_data):
        signupForms = validated_data.pop("signup_id", [])
        tags = validated_data.pop("tag_id")
        instance.signupForm.clear()
        instance.tags.clear()
        for form in signupForms:
            instance.signupForm.add(form)
        for tag in tags:
            instance.tags.add(tag)
        instance = super(EventSerializer, self).update(instance, validated_data)
        return instance


class SavedQuestionsSerializer(serializers.ModelSerializer):
    questions = serializers.JSONField()

    class Meta:
        model = TemplateQuestion
        fields = ("id", "name", "questions")


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ("id", "slug", "name_fi", "name_en", "icon")


class FeedSerializer(serializers.ModelSerializer):
    tag_id = serializers.PrimaryKeyRelatedField(
        many=True, source="tags", queryset=Tag.objects.all()
    )

    class Meta:
        model = Feed
        fields = (
            "id",
            "tags",
            "tag_id",
            "visible",
            "image",
            "title_fi",
            "title_en",
            "description_fi",
            "description_en",
            "content_fi",
            "content_en",
            "publish_time",
            "autohide",
            "autohide_enabled",
        )
        depth = 1

    def create(self, validated_data):
        tags_data = validated_data.pop("tags")
        feed = Feed.objects.create(**validated_data)
        for tag in tags_data:
            feed.tags.add(tag)
        feed.save()
        return feed


class JobAdSerializer(serializers.ModelSerializer):
    class Meta:
        model = JobAd
        fields = (
            "id",
            "title_fi",
            "title_en",
            "description_fi",
            "description_en",
            "content_fi",
            "content_en",
            "visible",
            "autohide_at",
            "autohide_enabled",
        )
