from rest_framework import serializers

from newsreader.news.collection.serializers import RuleSerializer
from newsreader.news.core.models import Category, Post


class PostSerializer(serializers.ModelSerializer):
    publicationDate = serializers.DateTimeField(
        source="publication_date", required=False
    )
    remoteIdentifier = serializers.CharField(source="remote_identifier", required=False)

    rule = RuleSerializer(read_only=True)

    class Meta:
        model = Post
        fields = (
            "id",
            "title",
            "body",
            "author",
            "url",
            "rule",
            "read",
            "saved",
            "publicationDate",
            "remoteIdentifier",
        )


class CategorySerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    unread = serializers.SerializerMethodField()

    def get_unread(self, category):
        return Post.objects.filter(
            rule__in=category.rules.values_list("pk", flat=True), read=False
        ).count()

    class Meta:
        model = Category
        fields = ("id", "name", "user", "unread")
