import datetime

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

from verify_trusted.blogs.models import PostCategory, PostTag, Blog

User = get_user_model()


class PostCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = PostCategory
        fields = '__all__'


class PostTagSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostTag
        fields = '__all__'


class BlogSerializer(serializers.ModelSerializer):
    category = serializers.PrimaryKeyRelatedField(
        required=False, read_only=False, queryset=PostCategory.objects.all()
    )
    tags = serializers.PrimaryKeyRelatedField(
        required=False, read_only=False, queryset=PostTag.objects.all()
    )

    class Meta:
        model = Blog

    def create(self, validated_data):
        blog = None
        self.create_category(validated_data.category)
        for t in validated_data.tag:
            self.create_tag(t)
        return blog

    def create_category(self, category):
        if category is not None:
            old_category = PostCategory.objects.filter(name=category).first()
            if old_category is None:
                category_data = {"name": category, "date_create": datetime.datetime.now()}
                category = PostCategory.objects.create(**category_data)
                category.save()

    def create_tag(self, tag):
        if tag is not None:
            old_category = PostTag.objects.filter(name=tag).first()
            if old_category is None:
                category_data = {"name": tag, "date_create": datetime.datetime.now()}
                category = PostTag.objects.create(**category_data)
                category.save()


class BlogUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username", "email", "name", 'is_superuser']


class BlogListSerializer(BlogSerializer):
    user = BlogUserSerializer()

    class Meta:
        model = Blog


class BlogFirstLetterSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog
        fields = (
            'id',
            'title',
            'summary',
            'body',
            'tags',
            'category',
            'date_create',
        )

class BlogUpdateSerializer(BlogSerializer):
    pass
