import lasso
import pytest
from django.contrib import auth

from docbow_project.docbow.models import DocbowProfile
from docbow_project.pfwb.mellon_adapter import PFWBMellonAdapter

User = auth.get_user_model()


@pytest.fixture
def saml_attributes():
    return {
        'name_id_format': lasso.SAML2_NAME_IDENTIFIER_FORMAT_PERSISTENT,
        'name_id_content': 'x' * 32,
        'issuer': 'http://idp5/metadata',
        'username': ['foobar'],
        'email': ['test@example.net'],
        'first_name': ['Foo'],
        'last_name': ['Bar'],
        'is_superuser': ['true'],
        'group': ['GroupA', 'GroupB', 'GroupC'],
    }


@pytest.fixture
def john(db):
    return User.objects.create(username='john.doe', email='john.doe@example.com')


def test_lookup_user_by_tabellio_pers_id(db, settings, saml_attributes, john):
    adapter = PFWBMellonAdapter()
    saml_attributes['tabellio_pers_id'] = '1234'
    DocbowProfile.objects.create(user=john, external_id='1234')
    user = adapter.lookup_user({}, saml_attributes)
    assert user.id == john.id


def test_lookup_user_if_no_profile(db, settings, saml_attributes):
    settings.MELLON_PROVISION = False
    adapter = PFWBMellonAdapter()
    saml_attributes['tabellio_pers_id'] = '1234'
    user = adapter.lookup_user({}, saml_attributes)
    assert user is None


def test_provision_creates_profile(db, settings, saml_attributes, john):
    adapter = PFWBMellonAdapter()
    saml_attributes['tabellio_pers_id'] = '1234'
    adapter.provision(john, {}, saml_attributes)
    assert john.docbowprofile.external_id == '1234'


def test_provision_populates_existing_profile(db, settings, saml_attributes, john):
    adapter = PFWBMellonAdapter()
    DocbowProfile.objects.create(user=john)
    saml_attributes['tabellio_pers_id'] = '1234'
    adapter.provision(john, {}, saml_attributes)
    assert john.docbowprofile.external_id == '1234'


def test_provision_update_existing_profile(db, settings, saml_attributes, john):
    adapter = PFWBMellonAdapter()
    DocbowProfile.objects.create(user=john, external_id='5678')
    saml_attributes['tabellio_pers_id'] = '1234'
    adapter.provision(john, {}, saml_attributes)
    assert john.docbowprofile.external_id == '1234'


def test_provision_no_update_if_empty_attribute(db, settings, saml_attributes, john):
    adapter = PFWBMellonAdapter()
    DocbowProfile.objects.create(user=john, external_id='5678')
    saml_attributes['tabellio_pers_id'] = ''
    adapter.provision(john, {}, saml_attributes)
    assert john.docbowprofile.external_id == '5678'
