#!/usr/bin/env python

"""
Compare files in a normalized way. Used by create_test for
diffing non-namelist files.
"""

import acme_util
acme_util.check_minimum_python_version(2, 7)

import argparse, sys, os

import simple_compare
from acme_util import expect, warning, verbose_print

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
usage="""\n%s <Path to gold namelist file> <Path to non-namelist file> [-c <CASEBASEID>] [--verbose]
OR
%s --help
OR
%s --test

\033[1mEXAMPLES:\033[0m
    \033[1;32m# Compare files\033[0m
    > %s baseline_dir/test/file mytestarea/file -c <CASE>
""" % ((os.path.basename(args[0]), ) * 4),

description=description,

formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

    parser.add_argument("gold_file", help="Path to gold file")

    parser.add_argument("new_file", help="Path to file to compare against gold")

    parser.add_argument("-c", "--case", action="store", dest="case", default=None,
                        help="The case base id (<TESTCASE>.<GRID>.<COMPSET>). Helps us normalize data.")

    parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False,
                        help="Print extra information")

    args = parser.parse_args(args[1:])

    acme_util.set_verbosity(args.verbose)

    # Normalize case
    if (args.case is not None):
        args.case = acme_util.normalize_case_id(args.case)

    return args.gold_file, args.new_file, args.case

###############################################################################
def _main_func(description):
###############################################################################
    if ("--test" in sys.argv):
        acme_util.run_cmd("python -m doctest %s/simple_compare.py -v" % os.path.dirname(sys.argv[0]), arg_stdout=None, arg_stderr=None)
        return

    if ("--test" in sys.argv):
        test_results = doctest.testmod(verbose=True)
        sys.exit(1 if test_results.failed > 0 else 0)

    acme_util.stop_buffering_output()

    gold_file, compare_file, case = \
        parse_command_line(sys.argv, description)

    if (case is None):
        warning("No case id data available, will not be able to normalize values as effectively")
    else:
        verbose_print("Using case: '%s'" % case)

    expect(simple_compare.compare_files(gold_file, compare_file, case),
           "Diff between files %s and %s" % (gold_file, compare_file))

    print "Files %s and %s MATCH" % (gold_file, compare_file)

###############################################################################

if (__name__ == "__main__"):
    _main_func(__doc__)
