from rest_framework import serializers
from account.models import User


class UserSerializer(serializers.ModelSerializer):
    nickname = serializers.CharField()
    email = serializers.CharField()
    confirmed_at = serializers.DateTimeField(allow_null=True)
    id = serializers.CharField()

    class Meta:
        model = User

        fields = (
            "id",
            "nickname",
            "email",
            "confirmed_at"
        )

    def validate(self, data):
        data["old_id"] = data.pop("id")
        data["username"] = self.get_username(data)
        data["email_confirmed"] = self.get_email_confirmed(data)
        data.pop("nickname")
        data.pop("confirmed_at")
        return data

    def create(self, validated_data):
        # использовать get_or_create
        User.objects.create(**validated_data)

    def get_email_confirmed(self, data):
        if data.get("confirmed_at"):
            return True
        else:
            return False

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