# Plone Intranet global test setup
from contextlib import contextmanager
from email import message_from_bytes
from email.header import decode_header
from importlib.resources import files
from plone import api
from plone.namedfile.file import NamedBlobFile
from plone.namedfile.file import NamedBlobImage

import logging
import quopri
import sys


def enableLogging(loglevel=logging.INFO):
    """Enable logging in unit tests.

    Add this somewhere in your test code::

        from ploneintranet.testing import enableLogging
        enableLogging()

    """
    logging.root.setLevel(loglevel)
    logging.root.addHandler(logging.StreamHandler(sys.stdout))


def dummy_file(filename="test.mp3"):
    data = (files("ploneintranet.tests") / filename).read_bytes()
    return NamedBlobFile(data=data, filename=filename)


def dummy_image(filename="test.png"):
    data = (files("ploneintranet.tests") / filename).read_bytes()
    return NamedBlobImage(data=data, filename=filename)


@contextmanager
def temporary_registry_record(key, value):
    """Temporarily set up a registry record"""
    pr = api.portal.get_tool("portal_registry")
    backup = pr._records[key].value
    pr._records[key].value = value
    try:
        yield value
    finally:
        pr._records[key].value = backup


class DummyMessage:
    def __init__(self, message):
        self.message = message_from_bytes(message)

    @property
    def to(self):
        return self.message["To"]

    @property
    def subject(self):
        return decode_header(self.message["Subject"])[0][0]

    @property
    def body(self):
        """Walk down the message to get the text version of the mail
        and extract is body
        """
        body = self.message.get_payload()[0].get_payload()[0].get_payload()
        return quopri.decodestring(body).decode("utf-8")
