import datetime
import io
import logging
import os
import shutil
from enum import Enum

import mock
import pytest

# Useless try/except to make flake8 happy \_("/)_/
try:
    from uaclient import event_logger
    from uaclient.config import UAConfig
    from uaclient.entitlements.entitlement_status import ApplicationStatus
    from uaclient.files.machine_token import MachineTokenFile
    from uaclient.files.notices import NoticeFileDetails
    from uaclient.files.user_config_file import UserConfigData
except ImportError:
    raise


shutil.get_terminal_size = mock.MagicMock(
    return_value=os.terminal_size((80, 20))
)


@pytest.yield_fixture(scope="session", autouse=True)
def _subp():
    """
    A fixture that mocks system._subp for all tests.
    If a test needs the actual _subp, this fixture yields it,
    so just add an argument to the test named "_subp".
    """
    from uaclient.system import _subp

    original = _subp
    with mock.patch(
        "uaclient.system._subp", return_value=("mockstdout", "mockstderr")
    ):
        yield original


@pytest.yield_fixture(scope="session", autouse=True)
def _warn_about_new_version():
    """
    A fixture that mocks cli._warn_about_new_version for all tests.
    If a test needs the actual _warn_about_new_version, this fixture yields it,
    so just add an argument to the test named "_warn_about_new_version".
    """
    from uaclient.cli import _warn_about_new_version

    original = _warn_about_new_version
    with mock.patch("uaclient.cli._warn_about_new_version"):
        yield original


@pytest.yield_fixture(scope="session", autouse=True)
def update_sources_list():
    """
    A fixture that mocks apt.update_sources_list for all tests.
    If a test needs the actual update_sources_list, this fixture yields it,
    so just add an argument to the test named "update_sources_list".
    """
    from uaclient.apt import update_sources_list

    original = update_sources_list
    with mock.patch("uaclient.apt.update_sources_list"):
        yield original


@pytest.yield_fixture(scope="session", autouse=True)
def util_we_are_currently_root():
    """
    A fixture that mocks util.we_are_currently_root for all tests.
    Default to true as most tests need it to be true.
    """
    from uaclient.util import we_are_currently_root

    original = we_are_currently_root
    with mock.patch("uaclient.util.we_are_currently_root", return_value=True):
        yield original


@pytest.yield_fixture(scope="session", autouse=True)
def urllib_request_urlopen():
    """
    A fixture that mocks urlopen for all tests.
    This prevents us from accidentally making requests in unit tests
    """
    from urllib.request import urlopen

    original = urlopen
    with mock.patch("urllib.request.urlopen"):
        yield original


@pytest.fixture
def caplog_text(request):
    """
    A fixture that returns a function that returns caplog.text

    caplog isn't available in pytest in all of our target releases; this either
    uses caplog.text if available, or a shim which replicates what it does.

    Specifically, bionic is the first Ubuntu release to contain a version of
    pytest new enough for the caplog fixture to be present. In xenial, the
    python3-pytest-catchlog package provides the same functionality (this is
    the code that was later integrated in to pytest).

    (It returns a function so that the requester can decide when to examine the
    logs; if it returned caplog.text directly, that would always be empty.)
    """
    cap_params = getattr(request, "param", logging.INFO)
    log_filter = None
    if isinstance(cap_params, tuple):
        log_level = cap_params[0]
        log_filter = cap_params[1]
    else:
        log_level = cap_params
    try:
        try:
            caplog = request.getfixturevalue("caplog")
        except AttributeError:
            # Older versions of pytest only have getfuncargvalue, which is now
            # deprecated in favour of getfixturevalue
            caplog = request.getfuncargvalue("caplog")
        caplog.set_level(log_level)
        if log_filter:
            caplog.handler.addFilter(log_filter())

        def _func():
            return caplog.text

    except LookupError:
        # If the caplog fixture isn't available, shim something in ourselves
        root = logging.getLogger("ubuntupro")
        root.propagate = False
        root.setLevel(log_level)
        handler = logging.StreamHandler(io.StringIO())
        handler.setFormatter(
            logging.Formatter(
                "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
            )
        )
        if log_filter:
            handler.addFilter(log_filter())
        root.addHandler(handler)

        def _func():
            return handler.stream.getvalue()

        def clear_handlers():
            root.handlers = []

        request.addfinalizer(clear_handlers)
    return _func


@pytest.yield_fixture
def logging_sandbox():
    # Monkeypatch a replacement root logger, so that our changes to logging
    # configuration don't persist outside of the test
    upro_logger = logging.getLogger("ubuntupro")
    upro_logger.setLevel(logging.WARNING)

    with mock.patch.object(logging, "root", upro_logger):
        with mock.patch.object(logging.Logger, "root", upro_logger):
            with mock.patch.object(
                logging.Logger, "manager", logging.Manager(upro_logger)
            ):
                yield


@pytest.yield_fixture(scope="function", autouse=True)
def fake_machine_token_file():
    from unittest.mock import patch

    with patch(
        "uaclient.files.machine_token.get_machine_token_file"
    ) as m_get_machine_token_file:
        machine_token = FakeMachineToken(attached=False)
        m_get_machine_token_file.return_value = machine_token
        yield machine_token


class FakeMachineToken(MachineTokenFile):
    def __init__(self, attached, token=None):
        self.attached = attached
        self._machine_token = None
        self.token = token
        self.machine_token_overlay_path = None
        self._contract_expiry_datetime = None
        self._entitlements = None
        self.write_calls = 0
        self.delete_calls = 0

    @property
    def machine_token(self):
        self._machine_token = None
        return super().machine_token

    @property
    def is_present(self):
        return self.attached

    def read(self):
        if self.token:
            return self.token

        if not self.attached:
            return None

        return {
            "availableResources": [],
            "machineToken": "not-null",
            "machineTokenInfo": {
                "machineId": "test_machine_id",
                "accountInfo": {
                    "id": "acct-1",
                    "name": "test",
                    "createdAt": datetime.datetime(
                        2019,
                        6,
                        14,
                        6,
                        45,
                        50,
                        tzinfo=datetime.timezone.utc,
                    ),
                    "externalAccountIDs": [{"IDs": ["id1"], "origin": "AWS"}],
                },
                "contractInfo": {
                    "id": "cid",
                    "name": "test_contract",
                    "createdAt": datetime.datetime(
                        2020,
                        5,
                        8,
                        19,
                        2,
                        26,
                        tzinfo=datetime.timezone.utc,
                    ),
                    "effectiveFrom": datetime.datetime(
                        2000,
                        5,
                        8,
                        19,
                        2,
                        26,
                        tzinfo=datetime.timezone.utc,
                    ),
                    "effectiveTo": datetime.datetime(
                        2040,
                        5,
                        8,
                        19,
                        2,
                        26,
                        tzinfo=datetime.timezone.utc,
                    ),
                    "resourceEntitlements": [],
                    "products": ["free"],
                },
            },
        }

    def write(self, private_content):
        self.token = private_content
        self.write_calls += 1

    def delete(self):
        self.delete_calls += 1


@pytest.fixture
def FakeConfig(tmpdir):
    class _FakeConfig(UAConfig):
        def __init__(
            self,
            cfg_overrides={},
            features_override=None,
        ) -> None:
            if not cfg_overrides.get("data_dir"):
                cfg_overrides.update({"data_dir": tmpdir.strpath})
            if not cfg_overrides.get("log_file"):
                cfg_overrides.update(
                    {"log_file": tmpdir.join("log_file.log").strpath}
                )
            super().__init__(
                cfg_overrides,
                user_config=UserConfigData(),
            )

        def override_features(self, features_override):
            if features_override is not None:
                self.cfg.update({"features": features_override})

    return _FakeConfig


@pytest.fixture
def event():
    event = event_logger.get_event_logger()
    event.reset()

    return event


class FakeNotice(NoticeFileDetails, Enum):
    reboot_required = NoticeFileDetails(
        "10", "reboot_required", False, "notice_a"
    )
    reboot_script_failed = NoticeFileDetails(
        "12", "reboot_script_failed", True, "notice_a2"
    )
    enable_reboot_required = NoticeFileDetails(
        "11", "enable_reboot_required", False, "notice_b"
    )


@pytest.yield_fixture(autouse=True)
def mock_notices_dir(tmpdir_factory):
    perm_dir = tmpdir_factory.mktemp("notices")
    temp_dir = tmpdir_factory.mktemp("temp_notices")
    with mock.patch(
        "uaclient.defaults.NOTICES_PERMANENT_DIRECTORY",
        perm_dir.strpath,
    ):
        with mock.patch(
            "uaclient.defaults.NOTICES_TEMPORARY_DIRECTORY",
            temp_dir.strpath,
        ):
            yield


@pytest.fixture
def mock_entitlement():
    def factory_func(
        *,
        name="test",
        title="test",
        application_status=(ApplicationStatus.DISABLED, ""),
        can_disable=(False, None),
        disable=(False, None),
        enable=(False, None)
    ):
        m_ent_cls = mock.MagicMock()
        type(m_ent_cls).name = mock.PropertyMock(return_value=name)
        m_ent_obj = m_ent_cls.return_value
        type(m_ent_obj).title = mock.PropertyMock(return_value=title)
        m_ent_obj.application_status.return_value = application_status
        m_ent_obj.disable.return_value = disable
        m_ent_obj.enable.return_value = enable
        m_ent_obj.can_disable.return_value = can_disable

        return (m_ent_cls, m_ent_obj)

    return factory_func
