import os
import pytest
from pathlib import Path
from oaa.app_runners.custom_app import CustomAppRunner

BASE_DIR = Path(os.path.dirname(os.path.realpath(__file__)))


@pytest.fixture
def _config(config):
    config.update(config_file=BASE_DIR / 'config2-multiple-transforms-one-field.yaml')

    return config


def test_source_should_have_multiple_transforms(_config):
    assert _config.config_file
    assert _config.sources
    source = _config.sources['users']
    assert len(source.field_mappings()['name'].transforms) == 2


def test_stream_and_get_stream_should_return_same_object(_config):

    source = _config.sources['users']

    assert id(source.stream) == id(source.get_stream())


def test_run_transforms_lowercase(_config):
    runner = CustomAppRunner()

    source = _config.sources['users']

    runner._run_transform(source)
    # runner.run()

    for r in source.records:
        assert 'email' in r.flds
        assert 'name' in r.flds
        assert 'id_here' in r.flds
        assert 'unique_id' in r.flds
        assert 'email_other_field' in r.flds
        assert r.name == r.name.lower()


def test_user_in_provider(_config):

    runner = CustomAppRunner()

    runner.run(push_to_oaa=False)

    provider = runner._provider_object

    username = 'khansen+samuel-chu-okta@veza.com'
    assert username in provider.local_users
    user = provider.local_users[username]

    assert user.properties['email_other_field'] == username


def test_source2(_config):
    runner = CustomAppRunner()
    runner._run_transforms()
    source2 = _config.sources['users2']
    print(source2._stream.fieldnames())

    for r in source2.records:
        assert 'new_field' in r.flds
        assert 'new_field2' in r.flds
        assert 'email2' in r.flds
        assert 'name2' in r.flds
        assert 'id_here2' in r.flds
        assert 'unique_id2' in r.flds
        assert r.name2 == r.name2.lower()
