from django.contrib.auth import get_user_model
from rest_framework import serializers

from webapp import models
from accounts import models as accounts_models


class _ArticleSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=200, required=True)
    text = serializers.CharField(max_length=3000, required=True)
    author_id = serializers.IntegerField(write_only=True)
    author = serializers.PrimaryKeyRelatedField(read_only=True)
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)

    def create(self, validated_data):
        return models.Article.objects.create(**validated_data)

    def update(self, instance, validated_data):
        for key, value in validated_data.items():
            setattr(instance, key, value)
        
        instance.save()
        return instance
    

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = accounts_models.Profile
        fields = ['birth_date', 'avatar']


class _UserSerializer(serializers.ModelSerializer):
    fullname = serializers.SerializerMethodField()
    class Meta:
        model = get_user_model()
        fields = ['id', 'fullname', 'first_name', 'last_name', 'email', 'username']

    def get_fullname(self, obj):
        return f'{obj.first_name} {obj.last_name}'


class ArticleSerializer(serializers.ModelSerializer):
    author = _UserSerializer(read_only=True)
    class Meta:
        model = models.Article
        fields = ['id', 'title', 'text', 'author', 'created_at', 'updated_at']


class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()
    articles = ArticleSerializer(many=True)
    
    class Meta:
        model = get_user_model()
        fields = ['id', 'first_name', 'last_name', 'email', 'username', 'profile', 'articles']
