import os
import unittest
import sys

if sys.version < '3':
    from StringIO import StringIO
else:
    from io import StringIO  # NOQA
try:
    import __builtin__
except ImportError:
    import builtins
    __builtin__ = builtins  # NOQA

# Make sure we'll find the required files...
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, "xmltreenode"))
sys.path.append(os.path.dirname(__file__))

import xmlparser


def __outputDiff(string_a, string_b, index_a, pos):
    """ Outputs differences in two strings, used by assertEqualString.
    Raises ValueError

    @param string_a First string
    @param string_b Second string
    @param index_a Index in first string
    @param pos Position of difference
    """
    msg = "String difference at %s:\n" % (index_a)
    ba = (index_a - 20)
    if ba < 0:
        ba = 0
    aa = (index_a + 10)
    if aa > len(string_a):
        aa = len(string_a)
    ab = (index_a + 10)
    if ab > len(string_b):
        ab = len(string_b)

    msg_a = string_a[ba:aa]
    msg_b = string_b[ba:ab]
    pos += msg_a.count('\n')
    msg += "\n" + msg_a.replace('\n', '\\n') + "\n"
    msg += msg_b.replace('\n', '\\n') + "\n"
    if index_a < pos:
        pos = index_a
    msg += '-' * pos + '^'

    raise ValueError(msg)


def assertEqualString(string_a, string_b, ignoreSpace=False, ignoreNewLine=False):
    """ Asserts that given two strings are equal.
    Return silently when ok, otherwise raises exception with verbosal output.

    @param string_a First string
    @param string_b Secondb string
    @param ignoreSpace When comparing strings, ignore all space characters
    @param ignoreNewLine When comparing strings, ignore all new line characters
    """

    if string_a is None and string_b is None:
        return
    if string_a is None:
        raise ValueError('First string is None')
    if string_b is None:
        raise ValueError('Second string is None')

    index_a = 0
    if ignoreSpace:
        string_a = string_a.replace(' ', '')
        string_b = string_b.replace(' ', '')
    if ignoreNewLine:
        string_a = string_a.replace('\n', '')
        string_b = string_b.replace('\n', '')
    while index_a < len(string_a) and index_a < len(string_b):
        if string_a[index_a] != string_b[index_a]:
            __outputDiff(string_a, string_b, index_a, 20)
        index_a += 1
    if len(string_a) != len(string_b):