"""
Feature tests for the user login feature.

:copyright: Copyright 2013-2015, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import pytest_bdd as bdd
from pytest_bdd import parsers


@bdd.scenario('user_login.feature', 'Allowed User can Login into Site')
def test_user_login_with_valid_credentials():
    pass


# TODO: Add in actual functionality to freeze the user info.

@bdd.given(parsers.parse('I am the {user_name} user with the {login_type} credentials'))
def user_credentials(user_name, login_type):
    USERS = {
        'admin': {'correct': 'password', 'incorrect': '123'},
        'hacker': {'correct': 'password', 'incorrect': 'hacking'},
    }
    password = USERS.get(user_name, {}).get(login_type, '')
    return user_name, password


@bdd.when('I navigate to the index page')
def navigate_to_page(browser, server_hostname, server_port):
    browser.visit('http://{host}:{port}/'.format(host=server_hostname, port=server_port))


@bdd.when('I am not logged in')
def login_state(browser):
    browser.execute_script('localStorage.removeItem("user_auth_token");')


@bdd.when('I click on the login button')
def press_on_login_logout_control(browser):
    # TODO Improve the ability for the web driver test to find the right element.
    # browser.find_by_text('Do you want to login?').first.click()
    # browser.find_link_by_partial_text('Do you want to login?').first.click()
    # browser.find_by_text('Hello Stranger!').first.click()
    # browser.find_by_text(' Do you want to').first.click()
    browser.find_by_id('user-login-trigger').first.click()


@bdd.when('I enter in my credentials')
def enter_credentials(browser, user_credentials):
    # TODO Submit changeset to react-bootstrap to include "name" parameters into input fields.
    username_text = browser.find_by_id('username')
    username_text.type(user_credentials[0])
    password_text = browser.find_by_id('password')
    password_text.type(user_credentials[1])


@bdd.when('I click login')
def click_user_login_modal_button(browser):
    browser.find_by_text('Login').first.click()


@bdd.then('I can see I am logged in')
def assert_user_logged_in(browser):
    # TODO Make this text easier to find
    # assert browser.is_text_present('Do you want to logout?')
    assert 'Do you want to logout?' in browser.find_by_id('user-login-trigger').first.text
