from rest_framework import serializers
from .models import RegisteredUser
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token


class RegisteredUserSerializer(serializers.ModelSerializer):
    email_address = serializers.SerializerMethodField()
    
    def get_email_address(self, obj):
        return obj.user.email

    class Meta:
        model = RegisteredUser
        exclude = ('user', 'has_nsfw_toggle')

class GetRegisteredUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegisteredUser
        exclude = ('user','created_at', 'updated_at', 'has_nsfw_toggle')

class CreateRegisteredUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = RegisteredUser
        exclude = ('user', )

class CreateRegisteredUserThroughUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'password', 'email', 'first_name', 'last_name')
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['email'],
            email=validated_data['email'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name']
        )

        user.set_password(validated_data['password'])
        user.save()

        reg_user = RegisteredUser.objects.create(
            phone_number=self.context.get("phone_number"),
            user=user,
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name']
        )
        Token.objects.create(user=user)
        return reg_user