# 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, "\n")

prices = read_prices("Data/prices.csv")
print("Prices:")
print(prices, "\n")

# ===========================================================
# Some cool map-reduction examples with list comprehensions
# ===========================================================

# *********************************************
# (1) Compute the total cost of the portfolio
# *********************************************

cost1 = 0
for p in portfolio:
   cost1 += p['shares'] * p['price']
print("cost1 = ", cost1, "\n")

cost = sum([ p['shares'] * p['price'] for p in portfolio ])
print("cost = ", cost, "\n")

print("Witness the map function: ", 
	[ p['shares'] * p['price'] for p in portfolio ],
	"\n" )

# *************************************************
# (2) Compute the current value of the portfolio
# *************************************************

value1 = 0
for p in portfolio:
   value1 += p['shares'] * prices[p['name']]
print("value1 = ", value1, "\n")

value = sum([ p['shares'] * prices[p['name']] for p in portfolio ])
print("value = ", value, "\n")


