import sys

def make_anonymous(id, anons):
    if anons.has_key(id):
        return anons[id]
    anon = 'ANONYMOUS%d' % len(anons)
    if sys.hexversion >= 0x2000000:
        anon = unicode(anon)
    anons[id] = anon
    return anon

def change_anonymous(statement, anonymous, anon_ids):
    if statement[0][:len(anonymous)] == anonymous:
        statement[0] = make_anonymous(statement[0], anon_ids)
    if statement[2][:len(anonymous)] == anonymous:
        statement[2] = make_anonymous(statement[2], anon_ids)
    return statement

def make_tuple(statements, source_uri):
    anons = {}
    anonymous = '%s#anonymous:' % source_uri
    result = []
    for statement in statements:
        stmt = [statement.subject,
                statement.predicate,
                statement.object,
                statement.uri,
                statement.sourceUri,
                ]
        change_anonymous(stmt, anonymous, anons)
        change_anonymous(stmt, 'anonymous:', anons)
        result.append(tuple(stmt))
    return result

def compare_tuple(expected, actual):
    if sys.hexversion >= 0x2000000:
        newExpected = []
        for old in expected:
            newExpected.append(tuple(map(lambda x:unicode(x),old)))
        expected = newExpected
    for stmt in expected:
        if stmt not in actual:
            print stmt
            return 1
        actual.remove(stmt)
    # Zero means equal
    return len(actual)

def print_tuple(statements):
    max_subj = len('subject')
    max_pred = len('predicate')
    max_obj = len('object')
    for statement in statements:
        subj = len(statement[0])
        pred = len(statement[1])
        obj = len(statement[2])
        if subj > max_subj: max_subj = subj
        if pred > max_pred: max_pred = pred
        if obj > max_obj: max_obj = obj

    print '%-*s | %-*s | %-*s' % (max_subj, 'subject',
                                  max_pred, 'predicate',
                                  max_obj, 'object',
                                  )
    print '-'*(max_subj + max_pred + max_obj + 6)

    for statement in statements:
        print '%-*s | %-*s | %-*s' % (max_subj, str(statement[0]),
                                      max_pred, str(statement[1]),
                                      max_obj, str(statement[2]),
                                      )
    return
