#
#  Copyright (c) 2018 Two Sigma Open Source, LLC
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to
#  deal in the Software without restriction, including without limitation the
#  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
#  sell copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
#  IN THE SOFTWARE.
#

'''Extends :mod:`unittest` to provide more information to the test
consumer on test failure. This additional information includes local
variables defined within the test at the time it failed, the full
assertion statement that failed, and a free-form annotation provided
by the test author. This additional information helps test consumers
respond to test failures without digging into the test code themselves.

To get this additional information in your tests, you can inherit
from :class:`marbles.core.TestCase` anywhere you would normally
inherit from :class:`unittest.TestCase`. By simply inheriting from
:class:`marbles.core.TestCase` instead, your test failures will
include the full assertion statement that failed and any local
variables in scope at the time the test failed.

Assertions on a :class:`marbles.core.TestCase` also accept an optional
``note`` string that will be exposed to the test consumer on test
failure. This annotation can contain whatever the test author feels is
important, but it is especially useful for communicating their intent
and any relevant context about the test. This annotation can be a
format string that will be expanded with local variables if/when the
test fails.

You can also inherit from :class:`marbles.core.AnnotatedTestCase`.
The only difference is that, if you inherit from
:class:`marbles.core.AnnotatedTestCase`, you must provide ``note``
annotations to all assertions. Calling an assertion without the
``note`` parameter on a :class:`marbles.core.AnnotatedTestCase`
will produce a :class:`marbles.core.AnnotationError`.
'''

import ast
import collections.abc
import functools
import inspect
import itertools
import linecache
import logging
import re
import sys
import textwrap
import unittest

from . import log
from . import _stack


_log = logging.getLogger(__name__)


# We subclass TextWrapper (instead of just writing a wrap()
# function) because we ultimately use TextWrapper.fill() to
# return the note as a wrapped string.
class _NoteWrapper(textwrap.TextWrapper):

    def wrap(self, text, **kwargs):
        '''Wraps each paragraph in ``text`` individually.

        Parameters
        ----------
        text : str

        Returns
        -------
        str
            Single string containing the wrapped paragraphs.
        '''
        pilcrow = re.compile(r'(\n\s*\n)', re.MULTILINE)
        list_prefix = re.compile(r'\s*(?:\w|[0-9]+)[\.\)]\s+')

        paragraphs = pilcrow.split(text)
        wrapped_lines = []
        for paragraph in paragraphs:
            if paragraph.isspace():
                wrapped_lines.append('')
            else:
                wrapper = textwrap.TextWrapper(**vars(self))
                list_item = re.match(list_prefix, paragraph)
                if list_item:
                    wrapper.subsequent_indent += ' ' * len(list_item.group(0))
                wrapped_lines.extend(wrapper.wrap(paragraph))

        return wrapped_lines


class _StatementFinder(ast.NodeVisitor):
    '''Finds the line of the statement containing a target line.

    For reasons passing understanding, :meth:`ast.walk` traverses the
    tree in breadth-first order rather than depth-first. In order to
    traverse depth-first (which we want), you have to implement a
    :class:`ast.NodeVisitor`.

    Startlingly, :meth:`ast.walk`'s documentation says that it