from rest_framework import serializers
from webapp.models import *


class SignupSerializer(serializers.ModelSerializer):
    signupForm_id = serializers.PrimaryKeyRelatedField(
        source="signupForm",
        queryset=SignupForm.objects.all()
    )
    answer = serializers.JSONField()
    list_name = serializers.CharField(read_only=True)

    def add_extra_fields(self, validated_data):
        questions = validated_data["signupForm"].questions
        validated_data["list_name"] = validated_data["answer"].get(questions[0]["id"], "")

        email_fields = list(filter(lambda x: x["type"] == "email", questions))
        if (len(email_fields) > 0):
            email_value = validated_data["answer"].get(email_fields[0]["id"], None)
            validated_data["email"] = email_value

    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', 'signupForm_id', 'answer', 'list_name')
        extra_kwargs = {
            'url': {
                'view_name': 'signup-detail',
            }
        }


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

    class Meta:
        model = SignupForm
        fields = ('id', 'title', 'start_time', 'end_time', 'questions', 'signups')


class EventSerializer(serializers.ModelSerializer):
    signupForm = SignupFormSerializer(many=True, read_only=True, required=False)
    signup_id = serializers.PrimaryKeyRelatedField(
        many=True,
        source="signupForm",
        queryset=SignupForm.objects.all()
    )
    tag_id = serializers.PrimaryKeyRelatedField(
        many=True,
        source="tags",
        queryset=Tag.objects.all()
    )

    class Meta:
        model = Event
        fields = ('id', 'tag_id', 'tags', 'visible', 'title_fi', 'title_en', 'description_fi', 'description_en',
                  'content_fi', 'content_en', 'start_time', 'end_time', 'location', 'signup_id', 'signupForm')
        depth = 1

    def create(self, validated_data):
        signupForms = validated_data.pop('signupForm')
        tags = validated_data.pop('tags')
        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('signupForm')
        instance = super(EventSerializer, self).update(instance, validated_data)
        instance.signupForm.clear()
        for form_data in signupForms:
            # form_qs = SignupForms.objects.filter(id=form['id'])
            instance.signupForm.add(form_data)
        return instance


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

    class Meta:
        model = TemplateQuestion
        fields = ('id', 'name', 'question')


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', '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 CommitteeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Committee
        fields = ['name_fi', 'name_en']


class RoleSerializer(serializers.ModelSerializer):
    committee = CommitteeSerializer(read_only=True)

    class Meta:
        model = Role
        fields = ('name_fi', 'name_en', 'description_fi', 'description_en', 'committee', 'is_board')


class ContactsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Official
        fields = ('first_name', 'last_name', 'email', 'phone_number', 'image')
        depth = 2


class OccupationSerializer(serializers.ModelSerializer):
    role = RoleSerializer(read_only=True)
    officials = ContactsSerializer(many=True, read_only=True)

    class Meta:
        model = Occupation
        fields = ('role', 'start_date', 'end_date', 'officials')
