import time

from .base import FunctionalTest

TEST_EMAIL = 'carlos@mockmyid.com'

class LoginTest(FunctionalTest):
    def test_login_with_persona(self):
        # Carlos goes to the site and notices a sign in link
        self.browser.get(self.server_url)
        self.browser.find_element_by_id('id_login').click()

        # A Persona login box appears
        self.switch_to_new_window('Mozilla Persona')

        # Carlos logs in with his e-mail address
        ## Use mockmyid.com for text email
        self.browser.find_element_by_id('authentication_email').send_keys(TEST_EMAIL)
        self.browser.find_element_by_tag_name('button').click()

        # The Persona window closes
        self.switch_to_new_window('To-Do')

        # He can see that he is logged in
        self.wait_to_be_logged_in(TEST_EMAIL)

        # Refreshing the page, the session is still active
        self.browser.refresh()
        self.wait_to_be_logged_in(TEST_EMAIL)

        # Click logout
        self.browser.find_element_by_id('id_logout').click()
        self.wait_to_be_logged_out(TEST_EMAIL)

        # The logged out status also persists after a refresh
        self.browser.refresh()
        self.wait_to_be_logged_out(TEST_EMAIL)


    def switch_to_new_window(self, text_in_title):
        retries = 60
        while retries > 0:
            for handle in self.browser.window_handles:
                self.browser.switch_to_window(handle)
                if text_in_title in self.browser.title:
                    return
            retries -= 1
            time.sleep(.5)
        self.fail('could not find window')
