#!/usr/bin/env python2
"""Execute the tests for the roi_intersect program.

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 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 roi_intersect'
    print '================================'
    print
    
    ph = app_tests.TestPathHelper(
        source_base, binary_base,
        'apps/ngs_roi/tests')  # tests dir

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

    path_to_project = app_tests.autolocateBinary(
      binary_base, 'apps/ngs_roi', 'roi_feature_projection')
    path_to_bam2roi = app_tests.autolocateBinary(
      binary_base, 'apps/ngs_roi', 'bam2roi')

    # ============================================================
    # Built TestConf list.
    # ============================================================

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

    # We prepare a list of transforms to apply to the output files.  This is
    # used to strip the input/output paths from the programs' output to
    # make it more canonical and host independent.
    ph.outFile('-')  # To ensure that the out path is set.
    transforms = [
        app_tests.ReplaceTransform(os.path.join(ph.source_base_path, 'apps/ngs_roi/tests') + os.sep, '', right=True),
        app_tests.ReplaceTransform(ph.temp_dir + os.sep, '', right=True),
        ]

    # ------------------------------------------------------------
    # Projection: Intersect with BED or GFF/GTF in BED style.
    # ------------------------------------------------------------

    for mode in ['projection', 'union', 'difference', 'intersection']:
        for fmt in ['bed', 'gff', 'gtf']:
            for ss_flag, ss_name in [('-ss', '_ss'), ('', '')]:
                conf = app_tests.TestConf(
                    program=path_to_project,
                    redir_stderr=ph.outFile('out_small_%s_m%s%s.stderr' % (fmt, mode, ss_name)),
                    redir_stdout=ph.outFile('out_small_%s_m%s%s.stdout' % (fmt, mode, ss_name)),
                    args=['-m', mode, ss_flag,
                          '-ir', ph.inFile('small.roi'),
                          '-if', ph.inFile('small.%s' % fmt),
                          '-or', ph.outFile('out_small_%s_m%s%s.roi' % (fmt, mode, ss_name))],
                    to_diff=[(ph.inFile('out_small_%s_m%s%s.stderr' % (fmt, mode, ss_name)),
                              ph.outFile('out_small_%s_m%s%s.stderr' % (fmt, mode, ss_name)),
                              transforms),
                             (ph.inFile('out_small_%s_m%s%s.stdout' % (fmt, mode, ss_name)),
                              ph.outFile('out_small_%s_m%s%s.stdout' % (fmt, mode, ss_name)),
                              transforms),
                             (ph.inFile('out_small_%s_m%s%s.roi' % (fmt, mode, ss_name)),
                              ph.outFile('out_small_%s_m%s%s.roi' % (fmt, mode, ss_name)),
                              transforms),
                             ])
                conf_list.append(conf)

    # TODO(holtgrew): Test with projection to transcripts.

    # ------------------------------------------------------------
    # BAM to ROI Conversion
    # ------------------------------------------------------------

    conf = app_tests.TestConf(
        program=path_to_bam2roi,
        redir_stderr=ph.outFile('out_mrna_2l_ss.roi.stderr'),
        redir_stdout=ph.outFile('out_mrna_2l_ss.roi.stdout'),
        args=['--strand-specific', '-if', ph.inFile('micro_rna_sorted_2l.bam'),
              '-of', ph.outFile('out_mrna_2l_ss.roi')],
        to_diff=[(ph.inFile('out_mrna_2l_ss.roi.stderr'), ph.outFile('out_mrna_2l_ss.roi.stderr'), transforms),
                 (ph.inFile('out_mrna_2l_ss.roi.stdout'), ph.outFile('out_mrna_2l_ss.roi.stdout'), transforms),
                 (ph.inFile('out_mrna_2l_ss.roi'), ph.outFile('out_mrna_2l_ss.roi'))
                 ])
    conf_list.append(conf)
    conf = app_tests.TestConf(
        program=path_to_bam2roi,
        redir_stderr=ph.outFile('out_mrna_2l.roi.stderr'),
        redir_stdout=ph.outFile('out_mrna_2l.roi.stdout'),
        args=['-if', ph.inFile('micro_rna_sorted_2l.bam'),
              '-of', ph.outFile('out_mrna_2l.roi')],
        to_diff=[(ph.inFile('out_mrna_2l.roi.stderr'), ph.outFile('out_mrna_2l.roi.stderr'), transforms),
                 (ph.inFile('out_mrna_2l.roi.stdout'), ph.outFile('out_mrna_2l.roi.stdout'), transforms),
                 (ph.inFile('out_mrna_2l.roi'), ph.outFile('out_mrna_2l.roi'))
                 ])
    conf_list.append(conf)

    # TODO(holtgrew): Test with paired-end data with/without ignoring pairing.

    # 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),
        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))
