from oaa.run import main
from pathlib import Path
from oaa.settings import Config
from oaa.settings_utils import SourceType
import pytest
import os


LOG_LEVELS = [
    'DEBUG',
    'INFO',
    'TRACE',
    'ERROR'
]


def test_run_help(capsys):

    main(cli_args=['custom_app', '--help'])

    captured = capsys.readouterr()

    output_expected = [
        'oaa', '--help',
        'COMMAND is one of the following:',
        ]

    for output in output_expected:
        # print(captured.out)
        assert output in captured.out

    # print('-' * 20)


def test_run_with_config(capsys):

    from pathlib import Path
    import os
    BASE_DIR = Path(os.path.dirname(os.path.realpath(__file__)))

    main(cli_args=['custom_app', 'show_config', '--config-file',
                   str(BASE_DIR / 'config-v2.yaml'),
                   '--config-file-yaml', 'true'])

    captured = capsys.readouterr()

    output_expected = [
        '"log_level"',
        'config_file',
    ]

    for output in output_expected:
        # print(captured.out)
        assert output in captured.out

    # print('-' * 20)


@pytest.mark.parametrize('log_level', LOG_LEVELS)
def test_new_singleton_config(log_level, config):
    os.environ['log_level'] = log_level
    assert os.getenv('log_level') == log_level
    config.update()
    assert Config.get('log_level') == log_level
    assert config.get('log_level') == log_level


@pytest.mark.parametrize('log_level', LOG_LEVELS)
def test_new_singleton_config_2(log_level, config):
    os.environ['log_level'] = log_level
    assert os.getenv('log_level') == log_level
    config.update()
    assert Config.get('log_level') == log_level
    assert config.LOG_LEVEL == log_level


def test_load_from_config_file(config):
    config.update(config_file='./tests/config-v2.yaml')

    assert config.LOG_LEVEL == 'ERROR'

    should_be = Path(os.path.dirname(__file__)) / 'data/resources_mapping.csv'
    assert config.sources['apps'].mapping_filepath == should_be


def test_mod_folder(config):
    '''
    We can write custom functions for manipulating data as needed.

    A mod function is created by decorating a function with the @transformer
    decorator found in oaa.utils

    The decorator takes two parameters:
    :table: the stream of data
    :config: the configuration object

    The mod function must return a streaming object
    '''
    from oaa.settings_v2 import ConfigV2

    config.update(config_file='./tests/config-v2.yaml',
                  config_format='yaml')
    assert config.version == 'v2'
    assert isinstance(config._CONFIG, ConfigV2)
    assert config.MODULE_DIRECTORY
    assert config.module_directory
    mod_folder_should_be = Path(os.path.dirname(__file__)) / 'modules'

    assert config.module_directory == mod_folder_should_be
