from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

from article.models import ArticlePost
from ckeditor.fields import RichTextField
from mptt.models import MPTTModel, TreeForeignKey


class Comment(MPTTModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comment')
    article = models.ForeignKey(ArticlePost, on_delete=models.CASCADE, related_name='comment')
    body = RichTextField()
    created = models.DateTimeField(default=timezone.now)  # 使用timezone.now()时 进行数据迁移会，有警告
    updated = models.DateTimeField(default=timezone.now)
    total_views = models.PositiveIntegerField(default=0)
    # mptt树形结构
    parent = TreeForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children'
    )
    # 记录二级评论回复给谁，str
    reply_to = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.CASCADE,
        related_name='replyers'
    )

    # class Meta:
    #    ordering = ('-created',)

    class MPTTMeta:
        order_insertion_by = ['created']

    def __str__(self):
        return self.body[:20]
