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

from .base import FunctionalTest
from .post_page import PostPage


class NewVisitorTest(FunctionalTest):
    # Test methods
    def test_can_start_a_post(self):
        self.create_pre_authenticated_session("alice@test.io")
        self.browser.get(self.live_server_url + '/billboard/')
        post_page = PostPage(self)

        self.assertIn('Earthman RPG', self.browser.title)
        header_text = self.browser.find_element(By.TAG_NAME, 'h1').text
        self.assertIn('Welcome', header_text)

        inputbox = post_page.get_line_input_box()
        self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a post line')

        inputbox.send_keys('Buy peacock feathers')

        inputbox.send_keys(Keys.ENTER)
        post_page.wait_for_row_in_post_table("Buy peacock feathers", 1)

        post_page.add_post_line("Use peacock feathers to make a fly")

        post_page.wait_for_row_in_post_table("Use peacock feathers to make a fly", 2)
        post_page.wait_for_row_in_post_table("Buy peacock feathers", 1)

    def test_multiple_users_can_start_posts_at_different_urls(self):
        self.create_pre_authenticated_session("alice@test.io")
        self.browser.get(self.live_server_url + '/billboard/')
        post_page = PostPage(self)
        post_page.add_post_line("Buy peacock feathers")

        edith_post_url = self.browser.current_url
        self.assertRegex(
            edith_post_url,
            r'/billboard/post/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/$',
        )

        self.browser.delete_all_cookies()

        self.create_pre_authenticated_session("disco@test.io")
        self.browser.get(self.live_server_url + '/billboard/')
        post_page = PostPage(self)
        page_text = self.browser.find_element(By.TAG_NAME, 'body').text
        self.assertNotIn('Buy peacock feathers', page_text)

        post_page.add_post_line("Buy milk")

        francis_post_url = self.browser.current_url
        self.assertRegex(
            francis_post_url,
            r'/billboard/post/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/$',
        )
        self.assertNotEqual(francis_post_url, edith_post_url)

        page_text = self.browser.find_element(By.TAG_NAME, 'body').text
        self.assertNotIn('Buy peacock feathers', page_text)
        self.assertIn('Buy milk', page_text)
