#!/usr/bin/env python3
"""Execute the tests for rabema.

The golden test outputs are generated by the script generate_outputs.sh.

You have to give the root paths to the source and the binaries as arguments to
the program.  These are the paths to the directory that contains the 'projects'
directory.

Usage:  run_tests.py SOURCE_ROOT_PATH BINARY_ROOT_PATH
"""
import logging
import os.path
import shutil
import sys

# Automagically add util/py_lib to PYTHONPATH environment variable.
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
                                    '..', '..', 'util', 'py_lib'))
sys.path.insert(0, path)

import seqan.app_tests as app_tests

def main(source_base, binary_base):
    """Main entry point of the script."""

    print('Executing test for rabema')
    print('=========================')
    print()
    
    ph = app_tests.TestPathHelper(
        source_base, binary_base,
        'apps/rabema/tests')  # tests dir

    # ============================================================
    # Auto-detect the binary path.
    # ============================================================

    path_to_prepare = app_tests.autolocateBinary(
      binary_base, 'apps/rabema', 'rabema_prepare_sam')
    path_to_build = app_tests.autolocateBinary(
      binary_base, 'apps/rabema', 'rabema_build_gold_standard')
    path_to_evaluate = app_tests.autolocateBinary(
      binary_base, 'apps/rabema', 'rabema_evaluate')

    # ============================================================
    # Copy Files To Temp Dir.
    # ============================================================

    # We copy over the genome because an FAI file will be created.
    shutil.copyfile(ph.inFile('adeno-genome.fa'),
                    ph.outFile('adeno-genome.fa'))

    # ============================================================
    # Build TestConf list.
    # ============================================================

    # Build list with TestConf objects, analoguely to how the output
    # was generated in generate_outputs.sh.
    conf_list = []

    # ============================================================
    # Prepare SAM
    # ============================================================

    conf = app_tests.TestConf(
        program=path_to_prepare,
        args=['-i', ph.inFile('gold-adeno-hamming-08.sam'),
              '-o', ph.outFile('gold-adeno-hamming-08.by_qname.sam')],
        to_diff=[(ph.inFile('gold-adeno-hamming-08.by_qname.sam'),
                  ph.outFile('gold-adeno-hamming-08.by_qname.sam'))])
    conf_list.append(conf)
    conf = app_tests.TestConf(
        program=path_to_prepare,
        args=['-i', ph.inFile('gold-adeno-edit-08.sam'),
              '-o', ph.outFile('gold-adeno-edit-08.by_qname.sam')],
        to_diff=[(ph.inFile('gold-adeno-edit-08.by_qname.sam'),
                  ph.outFile('gold-adeno-edit-08.by_qname.sam'))])
    conf_list.append(conf)

    # ============================================================
    # Build Gold Standard
    # ============================================================

    conf = app_tests.TestConf(
        program=path_to_build,
        redir_stdout=ph.outFile('gold-adeno-hamming-08.stdout'),
        args=['--distance-metric', 'hamming', '-e', '8',
              '-o', ph.outFile('gold-adeno-hamming-08.gsi'),
              '--reference', ph.outFile('adeno-genome.fa'),
              '--in-bam', ph.inFile('gold-adeno-hamming-08.by_coordinate.sam')],
        to_diff=[(ph.inFile('gold-adeno-hamming-08.stdout'),
                  ph.outFile('gold-adeno-hamming-08.stdout')),
                 (ph.inFile('gold-adeno-hamming-08.gsi'),
                  ph.outFile('gold-adeno-hamming-08.gsi'))])
    conf_list.append(conf)

    conf = app_tests.TestConf(
        program=path_to_build,
        redir_stdout=ph.outFile('gold-adeno-edit-08.stdout'),
        args=['--distance-metric', 'edit', '-e', '8',
              '-o', ph.outFile('gold-adeno-edit-08.gsi'),
              '--reference', ph.outFile('adeno-genome.fa'),
              '--in-bam', ph.inFile('gold-adeno-edit-08.by_coordinate.sam')],
        to_diff=[(ph.inFile('gold-adeno-edit-08.stdout'),
                  ph.outFile('gold-adeno-edit-08.stdout')),
                 (ph.inFile('gold-adeno-edit-08.gsi'),
                  ph.outFile('gold-adeno-edit-08.gsi'))])
    conf_list.append(conf)

    # ============================================================
    # Compare.
    # ============================================================

    conf = app_tests.TestConf(
        program=path_to_evaluate,
        redir_stdout=ph.outFile('razers2-adeno-hamming-08.stdout'),
        args=['--distance-metric', 'hamming', '-e', '8',
              '--reference', ph.outFile('adeno-genome.fa'),
              '--in-bam', ph.inFile('razers2-adeno-hamming-08.sam'),
              '--in-gsi', ph.inFile('gold-adeno-hamming-08.gsi')],
        to_diff=[(ph.inFile('razers2-adeno-hamming-08.stdout'),
                  ph.outFile('razers2-adeno-hamming-08.stdout'))])
    conf_list.append(conf)

    conf = app_tests.TestConf(
        program=path_to_evaluate,
        redir_stdout=ph.outFile('razers2-adeno-hamming-04.stdout'),
        args=['--distance-metric', 'hamming', '-e', '8',
              '--reference', ph.outFile('adeno-genome.fa'),
              '--in-bam', ph.inFile('razers2-adeno-hamming-04.sam'),
              '--in-gsi', ph.inFile('gold-adeno-hamming-08.gsi')],
        to_diff=[(ph.inFile('razers2-adeno-hamming-04.stdout'),
                  ph.outFile('razers2-adeno-hamming-04.stdout'))])
    conf_list.append(conf)

    conf = app_tests.TestConf(
        program=path_to_evaluate,
        redir_stdout=ph.outFile('razers2-adeno-edit-08.stdout'),
        args=['--distance-metric', 'edit', '-e', '8',
              '--reference', ph.outFile('adeno-genome.fa'),
              '--in-bam', ph.inFile('razers2-adeno-edit-08.sam'),
              '--in-gsi', ph.inFile('gold-adeno-edit-08.gsi')],
        to_diff=[(ph.inFile('razers2-adeno-edit-08.stdout'),
                  ph.outFile('razers2-adeno-edit-08.stdout'))])
    conf_list.append(conf)

    conf = app_tests.TestConf(
        program=path_to_evaluate,
        redir_stdout=ph.outFile('razers2-adeno-edit-04.stdout'),
        args=['--distance-metric', 'edit', '-e', '8',
              '--reference', ph.outFile('adeno-genome.fa'),
              '--in-bam', ph.inFile('razers2-adeno-edit-04.sam'),
              '--in-gsi', ph.inFile('gold-adeno-edit-08.gsi')],
        to_diff=[(ph.inFile('razers2-adeno-edit-04.stdout'),
                  ph.outFile('razers2-adeno-edit-04.stdout'))])

    conf_list.append(conf)

    # Execute the tests.
    failures = 0
    for conf in conf_list:
        res = app_tests.runTest(conf)
        # Output to the user.
        print(' '.join([os.path.basename(conf.program)] + conf.args), end=' ')
        if res:
             print('OK')
        else:
            failures += 1
            print('FAILED')

    # Cleanup.
    ph.deleteTempDir()

    print('==============================')
    print('     total tests: %d' % len(conf_list))
    print('    failed tests: %d' % failures)
    print('successful tests: %d' % (len(conf_list) - failures))
    print('==============================')
    # Compute and return return code.
    return failures != 0


if __name__ == '__main__':
    sys.exit(app_tests.main(main))
