import pytest

from fietsboek import models


@pytest.fixture()
def testuser(dbsession):
    """Provides and returns a test user."""
    user = models.User(email='foo@bar.com')
    user.set_password("foobar")
    dbsession.add(user)
    return user


def test_login_working(testapp, testuser, route_path):
    """Ensures that a verified user can log in with the right password."""
    testuser.is_verified = True

    login = testapp.get(route_path('login'))
    form = login.form
    form['email'] = 'foo@bar.com'
    form['password'] = 'foobar'
    response = form.submit().maybe_follow()

    assert b'Logout' in response.body


def test_login_not_verified(testapp, testuser, route_path):
    """Ensures that a user that has not yet verified their email address can
    not log in.
    """
    login = testapp.get(route_path('login'))
    form = login.form
    form['email'] = 'foo@bar.com'
    form['password'] = 'foobar'
    response = form.submit().maybe_follow()

    assert b'Logout' not in response.body
    assert b'not verified yet' in response.body


def test_login_wrong_email(testapp, testuser, route_path):
    """Ensures that a wrong email address won't let you log in."""
    login = testapp.get(route_path('login'))

    form = login.form
    form['email'] = 'fooooooooo@bar.com'
    form['password'] = 'foobar'
    response = form.submit().maybe_follow()

    assert b'Logout' not in response.body
    assert b'Invalid login credentials' in response.body


def test_login_wrong_password(testapp, testuser, route_path):
    """Ensures that a wrong password won't let you log in."""
    testuser.is_verified = True

    login = testapp.get(route_path('login'))
    form = login.form
    form['email'] = 'foo@bar.com'
    form['password'] = 'raboof'
    response = form.submit().maybe_follow()

    assert b'Logout' not in response.body
    assert b'Invalid login credentials' in response.body