# coding: utf-8


import difflib
import itertools

from pygments import highlight as pygments_highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import DiffLexer


def get_diff(old_text, new_text, full=False, highlight=True):
    """
    Возвращает построчный diff для двух текстов
    """
    # TODO: взять красивый diff из писем вики
    if full:
        context_lines = max(old_text.count('\n'), new_text.count('\n')) + 1
    else:
        context_lines = 3

    diff = difflib.unified_diff(
        old_text.splitlines() if old_text else [],
        new_text.splitlines() if new_text else [],
        n=context_lines,
    )
    diff = itertools.islice(diff, 2, None)
    diff = (line.strip('\n') for line in diff)
    diff = '\n'.join(diff)

    if highlight:
        diff = pygments_highlight(
            diff,
            DiffLexer(),
            HtmlFormatter(cssclass='source'),
        )

    return diff
