import sys
import textwrap

import pytest
import salt.modules.state as state
import salt.state
import salt.utils.files
import salt.utils.json
from tests.support.mock import MagicMock, patch

pytestmark = [
    pytest.mark.skipif(
        sys.version_info < (3, 6), reason="Dictionaries are not ordered under Py3.5"
    ),
]


@pytest.fixture
def configure_loader_modules(salt_minion_factory):
    return {
        state: {
            "__opts__": salt_minion_factory.config.copy(),
            "__salt__": {"saltutil.is_running": MagicMock(return_value=[])},
        },
    }


@pytest.fixture
def cachedir(tmp_path):
    path = tmp_path / "cache"
    path.mkdir()
    return path


@pytest.fixture
def fileserver_root(tmp_path):
    path = tmp_path / "fileserver-root"
    path.mkdir()
    return path


@pytest.fixture
def saltenvs():
    return ["base", "foo", "bar", "baz"]


@pytest.fixture
def saltenv_roots(fileserver_root, saltenvs):
    return {env: fileserver_root / env for env in saltenvs}


@pytest.fixture
def base_top_file(saltenv_roots):
    return str(saltenv_roots["base"] / "top.sls")


@pytest.fixture
def dunder_opts(saltenv_roots, saltenvs):
    return {
        "file_client": "local",
        "default_top": "base",
        "env_order": saltenv_roots,
        "file_roots": {
            "base": [str(saltenv_roots["base"])],
            "foo": [str(saltenv_roots["foo"])],
            "bar": [str(saltenv_roots["bar"])],
            "baz": [str(saltenv_roots["baz"])],
        },
    }


@pytest.fixture(autouse=True)
def state_tree(saltenv_roots, saltenvs):
    # Write top files for all but the "baz" environment
    for env, path in saltenv_roots.items():
        path.mkdir()
        if env == "baz":
            continue
        top_file = path / "top.sls"
        with salt.utils.files.fopen(str(top_file), "w") as fp_:
            # Add a section for every environment to each top file, with
            # the SLS target prefixed with the current saltenv.
            for env_name in saltenvs:
                fp_.write(
                    textwrap.dedent(
                        """\
                    {env_name}:
                      '*':
                        - {saltenv}_{env_name}
                    """.format(