import os
import pytest

from wurker.settings import conf
from wurker import ShowCommand

from .data.mock import TEST_BEES, TEST_CRONS


@pytest.fixture
def app_root():
    return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


@pytest.fixture
def etc_root():
    etc_root = ''
    if os.path.isdir(os.path.abspath(os.path.expanduser("~/.config/wurker/etc"))):
        etc_root = os.path.abspath(os.path.expanduser("~/.config/wurker/etc"))

    return etc_root


@pytest.fixture
def test_crons():
    return TEST_CRONS


@pytest.fixture
def test_bees():
    return TEST_BEES


def test_01_hive(app_root):
    """If a Wurker is running, this test SHOULD fail. Stop all wurkers first."""

    cmd = ShowCommand()
    hive = cmd.run("hive", return_result=True)
    assert len(hive) == 0


def test_02_command(etc_root):
    cmd = ShowCommand()
    commands = cmd.run("command", return_result=True)

    assert len(commands) == 2
    assert commands[0]["app_id"] == conf.app_id
    assert commands[0]["name"] == "Test Bee"
    assert commands[0]["slug"] == "test_bee"
    assert commands[0]["description"] == "A shell script for testing Wurker Bee commands"
    assert commands[0]["command"] == os.path.join(etc_root, "scripts", "test_bee.sh")
    assert commands[0]["is_module"] == False


def test_03_cron(test_crons):
    cmd = ShowCommand()
    crons = cmd.run("cron", return_result=True)

    assert len(crons) == 3

    for cron in crons:
        test_cron = test_crons[cron["slug"]]

        assert cron["app_id"] == conf.app_id
        assert cron["name"] == test_cron["name"]
        assert cron["slug"] == test_cron["slug"]
        assert cron["cron"] == test_cron["cron"]
        assert cron["overrun"] == test_cron["overrun"]


def test_04_bee(test_bees, etc_root):
    cmd = ShowCommand()
    bees = cmd.run("bee", return_result=True)

    assert len(bees) == 8

    for bee in bees:
        test_bee = test_bees[bee["slug"]]

        assert bee["app_id"] == conf.app_id
        assert bee["name"] == test_bee["name"]
        assert bee["slug"] == test_bee["slug"]
        assert bee["description"] == test_bee["description"]
        assert bee["quiet_restart"] == test_bee["quiet_restart"]
        assert bee["enabled"] == test_bee["enabled"]
        assert bee["module"] == test_bee["module"]
        assert bee["command_slug"] == test_bee["command_slug"]

        if bee["module"]:
            assert isinstance(bee["args"], dict)
        else:
            assert isinstance(bee["args"], list)

        assert bee["args"] == test_bee["args"]
