"""Notification app serializers."""
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from notification import models
from utils.methods import get_user_ip
from utils.serializers import TranslatedField


class SubscriptionTypeSerializer(serializers.ModelSerializer):
    """Subscription type serializer."""

    name_translated = TranslatedField()
    class Meta:
        """Meta class."""

        model = models.SubscriptionType
        fields = (
            'id',
            'index_name',
            'name_translated',
        )


class SubscribeSerializer(serializers.ModelSerializer):
    """Subscribe serializer."""

    email = serializers.EmailField(required=False, source='send_to')
    subscription_type = SubscriptionTypeSerializer(read_only=True)

    class Meta:
        """Meta class."""

        model = models.Subscriber
        fields = (
            'email',
            'subscription_type',
            'state',
        )
        read_only_fields = ('state',)

    def validate(self, attrs):
        """Validate attrs."""
        request = self.context.get('request')
        user = request.user

        # validate email
        email = attrs.get('send_to')
        if user.is_authenticated:
            if email is not None and email != user.email:
                raise serializers.ValidationError(_('Does not match user email'))
        else:
            if email is None:
                raise serializers.ValidationError({'email': _('This field is required.')})

        # append info
        attrs['email'] = email
        attrs['country_code'] = request.country_code
        attrs['locale'] = request.locale
        attrs['ip_address'] = get_user_ip(request)
        if user.is_authenticated:
            attrs['user'] = user

        subscription_type_id = self.context.get('request').parser_context.get('kwargs').get("subscription_type_pk")
        subscription_type_qs = models.SubscriptionType.objects.filter(id=subscription_type_id)
        if not subscription_type_qs.exists():
            raise serializers.ValidationError({'detail': _(f'SubscriptionType not found.')})
        attrs["subscription_type"] = subscription_type_qs.first()

        return attrs

    def create(self, validated_data):
        """Create obj."""
        subscriber = models.Subscriber.objects.make_subscriber(**validated_data)
        return subscriber
