import pytest

from wcs.qommon.ident.password_accounts import PasswordAccount
from utilities import get_app, login, create_temporary_pub, clean_temporary_pub


@pytest.fixture
def pub():
    pub = create_temporary_pub(sql_mode=False)
    pub.cfg['identification'] = {'methods': ['password']}
    pub.cfg['language'] = {'language': 'en'}
    pub.write_cfg()

    pub.user_class.wipe()
    PasswordAccount.wipe()

    user = pub.user_class()
    user.email = 'foo@localhost'
    user.store()
    account = PasswordAccount(id='foo')
    account.set_password('foo')
    account.user_id = user.id
    account.store()

    return pub

@pytest.fixture
def pub_2auth(pub):
    pub.cfg['identification'] = {'methods': ['password', 'idp']}
    pub.write_cfg()
    return pub

def teardown_module(module):
    clean_temporary_pub()

def test_login_logout(pub):
    resp_initial = get_app(pub).get('/')
    resp = login(get_app(pub), username='foo', password='foo').get('/')
    resp = resp.click('Logout')
    resp = resp.follow()
    assert resp.text == resp_initial.text

def test_register_account(pub):
    resp = get_app(pub).get('/').click('Login').follow()
    assert not 'register' in resp.text

    pub.cfg['identities'] = {'creation': 'self'}
    pub.write_cfg()
    resp = get_app(pub).get('/').click('Login').follow()
    assert 'register'in resp.text
    resp = resp.click('New Account page')
    resp.form['username'] = 'foobar'
    assert resp.form.submit().location == 'http://example.net/login/'
    assert PasswordAccount.count() == 2
    assert pub.user_class.count() == 2

def test_login_2auth(pub_2auth):
    resp = get_app(pub_2auth).get('/').click('Login').follow()
    resp.form['method'] = 'Username / password'
    resp = resp.form.submit().follow()
    resp.form['username'] = 'foo'
    resp.form['password'] = 'foo'
    resp = resp.form.submit().follow()
    assert '/logout' in resp.text

    resp = get_app(pub_2auth).get('/').click('Login').follow()
    resp.form['method'] = 'SAML identity provider'
    resp = resp.form.submit().follow()
    assert 'SSO support is not yet configured' in resp.text

def test_register_2auth(pub_2auth):
    pub_2auth.cfg['identities'] = {'creation': 'self'}
    pub_2auth.write_cfg()
    resp = get_app(pub_2auth).get('/register/')
    resp.form['method'] = 'Username / password'
    resp = resp.form.submit().follow()
    assert 'New Account' in resp.text

    resp = get_app(pub_2auth).get('/register/')
    resp.form['method'] = 'SAML identity provider'
    assert resp.form.submit().location == 'http://example.net/ident/idp/register'
