#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
import subprocess
import os
import sys
import re

tests = {
    'd2': [1, 1],
    'a': [1, 2, 0],
    'b': [1, 0, 0],
    'c': [1, 5],
    'd': [1, 0, 1],
    'e': [1, 0, 0, 0],
    'f': [1, 0, 0],
    'd3': [1, 0, 2],
    'd3-allzero': [1, 0, 2],
    'double-d3': [1, 0, 5],
    'double-d3-allzero': [1, 0, 5],
    'd4': [1, 0, 0, 9],
    'd4-allzero': [1, 0, 0, 9],
    'd5': [1, 0, 0, 0, 44],
    'd7': [1, 0, 0, 0, 0, 0, 1854],
    'medium-test-data': [14237, 39477, 378, 0],
    'd10': [1, 0, 0, 0, 0, 0, 0, 0, 0, 1334961]
}

zero_filtration = ['d3-allzero', 'double-d3-allzero', 'd4-allzero']

for filename, hom in tests.iteritems():
    print('Testing {filename}.flag...{spaces}\t\t'.format(
        filename=filename, spaces=(25 - len(filename)) * ' '), end='')
    try:
        os.remove('test/tmp')
    except OSError:
        pass
    result = ''.join(subprocess.Popen(
        'bash flagser --out ./test/tmp --filtration {alg} test/{filename}.flag'.format(
            alg="zero" if filename in zero_filtration else "max", filename=filename),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    ).stdout.readlines()).replace(',', '')

    success = True
    try:
        for idx, val in enumerate(hom):
            if re.search('dim H_{dim} = {rank}'.format(dim=idx, rank=val), result) == None:
                # The computation was wrong
                print('\x1b[0;31m' + 'Failure 𐄂' + '\x1b[0m')
                print('')
                print('\x1b[2m')
                sys.stdout.write(result)
                print('\x1b[0m')
                computed_rank = re.search(
                    'dim H_{dim} = (.*)$'.format(dim=idx), result, re.M).group(1)
                print('\x1b[0;31m' + 'The rank of H_{dim} should have been {rank}, but flagser computed {computed_rank}:'.format(
                    dim=idx, rank=val, computed_rank=computed_rank) + '\x1b[0m')
                print('\x1b[0m')
                success = False
                break
    except Exception as e:
        print("EXCEPTION: " + str(e))
        success = False

    if success:
        print('\x1b[0;32m' + 'Success ✔' + '\x1b[0m')
    else:
        raise ValueError("The test failed.")

# Cleanup
try:
    os.remove('test/tmp')
except OSError:
    pass
