# apps/comments/forms.py
from django import forms
from django.core.exceptions import ValidationError
from .models.comment import Comment


class CommentForm(forms.ModelForm):
    parent = forms.ModelChoiceField(queryset=Comment.objects.all(),
                                    required=False,
                                    widget=forms.HiddenInput())

    class Meta:
        model = Comment
        fields = ['content', 'parent']
        widgets = {
            'content':
            forms.Textarea(
                attrs={
                    'rows': 3,
                    'placeholder': '请输入您的评论（2000字以内）',
                    'class': 'comment-textarea'
                })
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        self.content_object = kwargs.pop('content_object', None)
        super().__init__(*args, **kwargs)

    def clean_parent(self):
        parent = self.cleaned_data.get('parent')
        if parent and parent.content_object != self.content_object:
            raise ValidationError("非法父评论")
        return parent

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.user = self.user
        instance.content_object = self.content_object
        if commit:
            instance.save()
        return instance
