import re
import quopri


class SignupHelper:

    def __init__(self, app):
        self.app = app

    def new_user(self, username, email, password):
        driver = self.app.driver
        driver.get(self.app.base_url + "/signup_page.php")
        driver.find_element_by_xpath("//input[@id='username']").send_keys(username)
        driver.find_element_by_xpath("//input[@id='email-field']").send_keys(email)
        driver.find_element_by_xpath("//input[@value='Signup']").click()

        encoded_mail = self.app.mail.get_mail(username, password, "[MantisBT] Account registration")
        decoded_mail = quopri.decodestring(encoded_mail).decode("utf-8")
        url = self.extract_confirmation_url(decoded_mail)

        driver.get(url)
        driver.find_element_by_id("password").send_keys(password)
        driver.find_element_by_id("password-confirm").send_keys(password)
        driver.find_element_by_xpath("//span[text()='Update User']").click()

    def extract_confirmation_url(self, text):
        return re.search("http://.*$", text, re.MULTILINE).group(0)
