# -*- encoding: utf-8 -*-
#
# ** header v3.0
# This file is a part of the LinkAhead Project.
#
# Copyright (C) 2018 Research Group Biomedical Physics,
# Max-Planck-Institute for Dynamics and Self-Organization Göttingen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header
#

from os import environ, getcwd, remove
from os.path import expanduser, isfile, join
from pathlib import Path

import linkahead as db
import pytest
from pytest import raises


@pytest.fixture
def temp_ini_files():
    created_temp_ini_cwd = False
    created_temp_ini_home = False
    if not isfile(join(getcwd(), "pylinkahead.ini")):
        open("pylinkahead.ini", 'a').close()  # create temporary ini file
        created_temp_ini_cwd = True
    if not isfile(expanduser("~/.pylinkahead.ini")):
        open(expanduser("~/.pylinkahead.ini"), 'a').close()  # create temporary ini file in home directory
        created_temp_ini_home = True
    yield 0
    if created_temp_ini_cwd:
        remove("pylinkahead.ini")
    if created_temp_ini_home:
        remove(expanduser("~/.pylinkahead.ini"))
    environ["PYLINKAHEADINI"] = "~/.pylinkahead.ini"


def test_config_ini_via_envvar(temp_ini_files):

    with raises(KeyError):
        environ["PYLINKAHEADINI"]

    environ["PYLINKAHEADINI"] = "bla bla"
    assert environ["PYLINKAHEADINI"] == "bla bla"
    # test wrong configuration file in envvar
    with pytest.raises(RuntimeError):
        db.configuration._read_config_files()
    # test good configuration file in envvar
    environ["PYLINKAHEADINI"] = "~/.pylinkahead.ini"
    assert expanduser("~/.pylinkahead.ini") in db.configuration._read_config_files()
    # test without envvar
    environ.pop("PYLINKAHEADINI")
    assert expanduser("~/.pylinkahead.ini") in db.configuration._read_config_files()
    # test configuration file in cwd
    assert join(getcwd(), "pylinkahead.ini") in db.configuration._read_config_files()


def test_config_timeout_option():
    expected_results = [None, (1, 20)]
    # Iterate through timeout test configs
    test_configs = Path(__file__).parent/'test_configs'
    for test_config in test_configs.rglob('pylinkahead-timeout*.ini'):
        # Test that test configs can be parsed
        db.configure(str(test_config))
        dct = db.configuration.config_to_yaml(db.get_config())
        # Test that resulting dict has correct content for timeout
        assert 'Connection' in dct
        assert 'timeout' in dct['Connection']
        assert dct['Connection']['timeout'] in expected_results
        expected_results.remove(dct['Connection']['timeout'])