"""Module for the asteex reporter to log results."""

import logging

from asteex.abstract.reporter import Reporter, ReportError


class LogReporter(Reporter):
    # pylint: disable=too-few-public-methods
    """Class for a reporter that uses the standard logger to report results."""

    async def report(self, results):
        """Report test results.

        :param results: async iterable with :class:`Results <asteex.abstract.result.Result>`.
        :raises: :class:`ReportError <asteex.abstract.reporter.ReportError>`.
        """
        logger = logging.getLogger(__name__)
        logger.debug("Start reporting test results with %s.", self)

        try:
            async for result in results:
                try:
                    instance_id = str(result.get_instance().get_id())
                except Exception as error:
                    logger.exception("Failed to get instance identifier from a test result.")
                    raise ReportError(
                        "Failed to get instance identifier from a test result",
                    ) from error

                try:
                    status = str(result.get_status())
                except Exception as error:
                    logger.exception("Failed to get status from a test result.")
                    raise ReportError("Failed to get status from a test result") from error

                try:
                    exception_information = tuple(result.get_exception_information())
                except Exception as error:
                    logger.exception("Failed to get exception information from a test result.")
                    raise ReportError(
                        "Failed to get exception information from a test result",
                    ) from error

                keyword_arguments = {}
                if exception_information != (None, None, None):
                    keyword_arguments["exc_info"] = exception_information

                logger.info(
                    "Execution of test instance '%s' finished with status '%s'.",
                    instance_id,
                    status,
                    **keyword_arguments,
                )
        except ReportError:
            raise
        except Exception as error:
            logger.exception("Failed to iterate over results.")
            raise ReportError("Failed to iterate over results") from error

        logger.info("Reported all test results with %s.", self)
