"""
Compares the tables generated by makeMiniAppTable and the
 corresponding table from the original mini app.
"""

import csv
import sys

from tr55.tablelookup import lookup_nlcd


# Generate keys from rows that will be used to match rows in the
# old and new table.
# If transform == True, convert values of row so that
# land and soil_types are in the format of the data table
# from the old mini-app
def get_key(row, transform=False):
    P = row['P']
    land = row['land']
    soil = row['soil']
    if transform:
        land = str(lookup_nlcd(row['land']))
        new_soil_types = ['a', 'b', 'c', 'd']
        old_soil_types = ['0', '1', '2', '3']
        soil_types_map = dict(zip(new_soil_types, old_soil_types))
        soil = soil_types_map[row['soil']]

    return (P, land, soil)


def isClose(val1, val2):
    val1 = round(float(val1), 1)
    val2 = round(float(val2), 1)
    return val1 == val2


def rowsMatch(old_row, new_row):
    return isClose(old_row['ET'], new_row['ET']) and \
        isClose(old_row['I'], new_row['I']) and \
        isClose(old_row['R'], new_row['R'])


def test_get_key():
    old_row = {'land': '71', 'I': '1.6', 'soil': '2',
               'P': '2.0', 'R': '0.2', 'ET': '0.1'}
    new_row = {'land': 'grassland', 'I': '1.6100773216841155',
               'soil': 'c', 'P': '2.0', 'R': '0.2657226783158845',
               'ET': '0.12419999999999999'}
    assert get_key(old_row) == get_key(new_row, transform=True) \
                            == ('2.0', '71', '2')


test_get_key()

if len(sys.argv) != 3:
    print ('Usage: python -m tr55.compareMiniAppTable ' +
           'old_csv_file_name new_csv_file_name')
    sys.exit()
else:
    old_csv_fn = sys.argv[1]
    new_csv_fn = sys.argv[2]

with open(old_csv_fn, 'rb') as old_csv_file:
    with open(new_csv_fn, 'rb') as new_csv_file:
        old_reader = csv.DictReader(old_csv_file)
        new_reader = csv.DictReader(new_csv_file)

        old_row_dict = dict([(get_key(old_row), old_row)
                             for old_row in old_reader])
        new_row_dict = dict([(get_key(new_row, transform=True), new_row)
                             for new_row in new_reader])

        num_in_match_rows = 0
        num_in_out_match_rows = 0
        for key, new_row in new_row_dict.iteritems():
            if key in old_row_dict:
                old_row = old_row_dict[key]
                if rowsMatch(old_row, new_row):
                    num_in_out_match_rows += 1
                else:
                    print 'output does not match'
                    print 'old row: ', old_row
                    print 'new row: ', new_row
                    print
                num_in_match_rows += 1

        print '# rows in new table: ', len(new_row_dict)
        print '# rows where input matches: ', num_in_match_rows
        print '# rows where input and output match: ', num_in_out_match_rows
