import csv


def load_data(path="./input/Border_Crossing_Entry_Data.csv"):
    """
    Reads data from the input csv file. The header with column names is skipped.
    Columns that are selected - Border, Date, Measure & Value fields.
    Also, counts total monthly border crossings per border/measure and saves it
    to a list as 'Crossing Entity' dictionary for further processing.
    """
    print("---> Loading data...")

    # "idx_list" keeps track of indicies of crossing entity objects in 'crossings_list'
    idx_list = []
    # each item in 'crossings_list' is a dictionary that holds a crossing entity object
    crossings_list = []

    try:
        with open(path) as csvFile:
            csvData = csv.reader(csvFile)
            #skip the header
            next(csvData, None) 
            for row in csvData:
                border = row[3]
                date = row[4] 
                measure = row[5]
                value = int(row[6])

                key = border + ',' + date + ',' + measure

                if key in idx_list:
                    idx = idx_list.index(key)
                    crossings_list[idx]["Value"] += value
                else:
                    idx_list.append(key)
                    crossing_entity = {
                                        "Date"   : date,
                                        "Border" : border,
                                        "Measure": measure,
                                        "Value"  : value
                                      }
                    crossings_list.append(crossing_entity)
    except OSError as e:
        print("Failed to read the input csv file!")
        print("I/O error({0}): {1}".format(e.errno, e.strerror))
        return

    # print("\n# of crossing entries: ", len(crossings_list))
    # print_list(crossings_list)
    print("     Finished!\n")
    return crossings_list