from django.test import TestCase

from apps.billboard.forms import (
    DUPLICATE_LINE_ERROR,
    EMPTY_LINE_ERROR,
    ExistingPostLineForm,
    LineForm,
)
from apps.billboard.models import Line, Post
from apps.lyric.models import User


class LineFormTest(TestCase):
    def setUp(self):
        self.author = User.objects.create(email="author@test.io")

    def test_form_save_handles_saving_to_a_post(self):
        mypost = Post.objects.create()
        form = LineForm(data={"text": "do re mi"})
        self.assertTrue(form.is_valid())
        new_line = form.save(for_post=mypost, author=self.author)
        self.assertEqual(new_line, Line.objects.get())
        self.assertEqual(new_line.text, "do re mi")
        self.assertEqual(new_line.post, mypost)

class ExistingPostLineFormTest(TestCase):
    def setUp(self):
        self.author = User.objects.create(email="author@test.io")

    def test_form_validation_for_blank_lines(self):
        post = Post.objects.create()
        form = ExistingPostLineForm(for_post=post, data={"text": ""})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors["text"], [EMPTY_LINE_ERROR])

    def test_form_validation_for_duplicate_lines(self):
        post = Post.objects.create()
        Line.objects.create(post=post, text="twins, basil", author=self.author)
        form = ExistingPostLineForm(for_post=post, data={"text": "twins, basil"})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors["text"], [DUPLICATE_LINE_ERROR])

    def test_form_save(self):
        mypost = Post.objects.create()
        form = ExistingPostLineForm(for_post=mypost, data={"text": "howdy"})
        self.assertTrue(form.is_valid())
        new_line = form.save(author=self.author)
        self.assertEqual(new_line, Line.objects.get())
