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

# test that a configuration can identify multiple DB sources (queries), pull
# that data into streams (petl.fromdb) and feed into OAA

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


@pytest.fixture
def multi_db_stream_config(config):
    config.update(
        config_file=BASE_DIR / "config-v2-2.yaml",
        config_format="yaml",
        config_version="v2",
    )

    return config


def test_config_app(multi_db_stream_config):
    config = multi_db_stream_config
    assert config.version == "v2"
    assert config.app


@pytest.fixture
def runner(multi_db_stream_config):

    yield CustomAppRunner()


def test_transformer_api(runner, multi_db_stream_config):
    source = multi_db_stream_config.sources["random_users"]
    runner._run_transform(source)
    assert source.stream

    for r in source.records:
        # print(r.name)
        assert isinstance(r["name"], str)
        assert r["unique_id"]


def test_api_responses(runner):
    """TODO: Docstring for test_api_responses.

    :multi_db_stream_config: TODO
    :returns: TODO

    """

    runner.run(push_to_oaa=False)

    oaa_app = runner._provider_object
    assert oaa_app
    assert len(oaa_app.local_users) == 10
    # there should be more users now


def test_fetch_module(runner):
    from oaa.settings_config import APIConnection

    connection = APIConnection(
        uri="https://randomuser.me/api/",
        method="get",
        params={"page": 1, "results": 8, "seed": "wonky"},
        max_results=15,
        fetch_module="api_fetch",
    )
    results = connection.fetch()

    assert results.nrows() == 15
