from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

from .base import FunctionalTest
from .post_page import PostPage


class LineValidationTest(FunctionalTest):
    # Helper functions
    def get_error_element(self):
        return self.browser.find_element(By.CSS_SELECTOR, ".invalid-feedback")

    # Test methods
    def test_cannot_add_empty_post_lines(self):
        self.create_pre_authenticated_session("disco@test.io")
        self.browser.get(self.live_server_url + '/billboard/')
        post_page = PostPage(self)
        post_page.get_line_input_box().send_keys(Keys.ENTER)

        self.wait_for(
            lambda: self.browser.find_element(By.CSS_SELECTOR, 'input[name="text"]:invalid')
        )

        post_page.get_line_input_box().send_keys("Purchase milk")
        self.wait_for(
            lambda: self.browser.find_element(By.CSS_SELECTOR, 'input[name="text"]:valid')
        )

        post_page.get_line_input_box().send_keys(Keys.ENTER)
        post_page.wait_for_row_in_post_table("Purchase milk", 1)

        post_page.get_line_input_box().send_keys(Keys.ENTER)

        post_page.wait_for_row_in_post_table("Purchase milk", 1)
        self.wait_for(
            lambda: self.browser.find_element(By.CSS_SELECTOR, 'input[name="text"]:invalid')
        )

        post_page.get_line_input_box().send_keys("Make tea")
        self.wait_for(
            lambda: self.browser.find_element(
                By.CSS_SELECTOR,
                'input[name="text"]:valid',
            )
        )
        post_page.get_line_input_box().send_keys(Keys.ENTER)
        post_page.wait_for_row_in_post_table("Make tea", 2)

    def test_cannot_add_duplicate_lines(self):
        self.create_pre_authenticated_session("disco@test.io")
        self.browser.get(self.live_server_url + '/billboard/')
        post_page = PostPage(self)
        post_page.add_post_line("Witness divinity")

        post_page.get_line_input_box().send_keys("Witness divinity")
        post_page.get_line_input_box().send_keys(Keys.ENTER)

        self.wait_for(
            lambda: self.assertEqual(
                self.get_error_element().text,
                "You've already logged this to your post",
            )
        )

    def test_error_messages_are_cleared_on_input(self):
        self.create_pre_authenticated_session("disco@test.io")
        self.browser.get(self.live_server_url + '/billboard/')
        post_page = PostPage(self)
        post_page.add_post_line("Gobbledygook")
        post_page.get_line_input_box().send_keys("Gobbledygook")
        post_page.get_line_input_box().send_keys(Keys.ENTER)
        self.wait_for(
            lambda: self.assertTrue(self.get_error_element().is_displayed())
        )

        post_page.get_line_input_box().send_keys("a")

        self.wait_for(
            lambda: self.assertFalse(self.get_error_element().is_displayed())
        )
