from django.db.models import fields
from rest_framework import serializers
from .models import User,UserProfile

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('dob','address','company')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    profile = UserProfileSerializer(required=True)

    class Meta:
        model = User
        fields = ('id','url','email','first_name','last_name','password','profile')
        extra_kwargs = {'password':{'write_only':True}}

    def create(self,validated_data):
        profile_data = validated_data.pop('profile')
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password) #password is hashes and stored as a hash
        user.save()
        UserProfile.objects.create(user=user,**profile_data)
        return user

    def update(self,instance,validated_data):
        profile_data = validated_data.pop('profile')
        profile = instance.profile

        instance.email = validated_data.get('email',instance.email)
        instance.save()

        profile.dob = profile_data.get('dob',profile.dob)
        profile.address = profile_data.get('address',profile.address)
        profile.company = profile_data.get('company',profile.company)
        profile.save()

        return instance