# fileparse.py
#
# Exercise 3.3, 3.4
#
# https://dabeaz-course.github.io/practical-python/Notes/03_Program_organization/02_More_functions.html
#


import csv

def parse_csv(filename, select=None, types=None):
    '''
    Parse a CSV file into a list of records
    '''

    with open(filename) as f:
        rows = csv.reader(f)

        # Read the file headers
        headers = next(rows)

        # Process selection
        if select:
            indices = [headers.index(colname) for colname in select]
            headers = select
#
# select is already a list...
#
# I did it the harder way:
#           headers = [ headers[index] for index in indices ]
        else:
            indices = [] 

        # Process data rows
        records = []
        for row in rows:
            if not row:    # Skip rows with no data
                continue

            # Filter the row if specific columns given
            if indices:
                row = [ row[index] for index in indices ]

            # Convert types if specified
            if types:
                row = [func(val) for func, val in zip(types, row) ]

            record = dict(zip(headers, row))
            records.append(record)

    return records



portfolio = parse_csv('Data/portfolio.csv', select=['name','shares'])
print(portfolio)

print()

portfolio = parse_csv('Data/portfolio.csv', types=[str,int,float])
print(portfolio)
