from django import forms

from .models import Line


DUPLICATE_LINE_ERROR = "You've already logged this to your post"
EMPTY_LINE_ERROR = "You can't have an empty post line"


class LineForm(forms.Form):
    text = forms.CharField(
        error_messages={"required": EMPTY_LINE_ERROR},
        required=True,
    )

    def save(self, for_post, author):
        return Line.objects.create(
            post=for_post,
            text=self.cleaned_data["text"],
            author=author,
        )


class ExistingPostLineForm(LineForm):
    def __init__(self, for_post, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._for_post = for_post

    def clean_text(self):
        text = self.cleaned_data["text"]
        if self._for_post.lines.filter(text=text).exists():
            raise forms.ValidationError(DUPLICATE_LINE_ERROR)
        return text

    def save(self, author):
        return super().save(for_post=self._for_post, author=author)
