# report.py
#
# Exercise 2.18

import csv

def read_portfolio(filename):
    '''Read a portfolio file'''

    data = list()        # return data as a list of dictionaries

    with open(filename, 'rt') as f:
        csv_f = csv.reader(f)

        # Read the header line (and discard)
        header = next(csv_f)
#       print(header)
#       print(type(header))

        # Read all data rows (and save in data)
        for row in csv_f:
#           print(row)        # row is a list
#           print(type( row) )
            row = [row[0], int(row[1]), float(row[2])]
#                          ^^^^^^^^ Convert the string data to numeric !!
            r = zip( header, row )	# Prepare to make a dictionary

            data.append(dict(r))   
    return data


def read_prices(filename):
    '''Read a stock prices file
       Format:  "stockName", price(f)
    '''

    data = dict()        # return data as a dictionary

    with open(filename, 'rt') as f:
        csv_f = csv.reader(f)

        # This CSV file does NOT have a header !!!

        # Read all data rows (and save in data)
        for row in csv_f:
#           print(row)        # row is a list
            if ( len(row) > 0 ):
               d = [row[0], float(row[1])]
#                        ^^^^^^^^ Convert the string data to numeric !!
#              print("d is a: ", type(d) )
#              print(d)         

               data[d[0]] = d[1]	# Add new (key,val) pair to dict
    return data


portfolio = read_portfolio("Data/portfolio.csv")

print("Portfolio:")
print(portfolio)

# tabulate the total number of shares of each stock.
from collections import Counter

holdings = Counter()		# Constructor

for s in portfolio:
   holdings[s['name']] += s['shares']

print("Holdings:")
print(holdings)
