from django.db import IntegrityError
from rest_framework import serializers

from account.models import User
from notification.models import Subscriber


class SubscriberSerializer(serializers.ModelSerializer):
    email = serializers.CharField()
    locale = serializers.CharField(allow_null=True)
    country_code = serializers.CharField(allow_null=True)

    class Meta:
        model = Subscriber
        fields = (
            "email",
            "locale",
            "country_code"
        )

    def validate(self, data):
        data["email"] = self.get_email(data)
        data["locale"] = self.get_locale(data)
        data["country_code"] = self.get_country_code(data)
        return data

    def create(self, validated_data):
        inst, created = Subscriber.objects.get_or_create(**validated_data)
        return inst

    def get_email(self, obj):
        return obj["email"]

    def get_locale(self, obj):
        return obj["locale"]

    def get_country_code(self, obj):
        return obj["country_code"]


class NewsletterSubscriberSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    email_address__email = serializers.CharField()
    email_address__account_id = serializers.IntegerField(allow_null=True)
    email_address__ip = serializers.CharField(allow_null=True, allow_blank=True)
    email_address__country_code = serializers.CharField(allow_null=True, allow_blank=True)
    email_address__locale = serializers.CharField(allow_null=True, allow_blank=True)
    updated_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S')

    def validate(self, data):
        data.update({
            'old_id': data.pop('id'),
            'email': data.pop('email_address__email'),
            'ip_address': data.pop('email_address__ip'),
            'country_code': data.pop('email_address__country_code'),
            'locale': data.pop('email_address__locale'),
            'created': data.pop('updated_at'),
            'user_id': self.get_user(data),
        })
        data.pop('email_address__account_id')
        return data

    def create(self, validated_data):
        try:
            obj = Subscriber.objects.get(email=validated_data['email'])
        except Subscriber.DoesNotExist:
            obj = Subscriber.objects.create(**validated_data)
        else:
            current_data = obj.created
            if validated_data['created'] > current_data:
                obj.ip_address = validated_data['ip_address']
                obj.locale = validated_data['locale']
                obj.country_code = validated_data['country_code']
                obj.old_id = validated_data['old_id']
                obj.created = validated_data['created']
                obj.user_id = validated_data['user_id']
                obj.save()
        return obj

    @staticmethod
    def get_user(data):

        if not data['email_address__account_id']:
            return None

        user = User.objects.filter(old_id=data['email_address__account_id']).first()
        if user:
            return user.id
        return None
