# report.py
#
# Exercise 2.4

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)

# =============================
# iterate over a list
# =============================
total = 0.0
for s in portfolio:
    total += s["shares"] * s["price"]  
print()
print("Total cost = ", total)
print()

import pprint				# Names are in "pprint" space
pprint.pprint(portfolio)

# NOT recommended: (ruin your main name space !!!)
# from pprint import * 

from pprint import pprint               # Name is in "main" space
pprint(portfolio)


# =============================
# iterate over a list
# =============================
#total = 0.0
#for name, numShares, price in portfolio: # Unpack a tuple
#    total += numShares * price     # Used the unpacked fields...
#print("Total cost = ", total)

print()

prices = read_prices("Data/prices.csv")
pprint(prices)


# ************************************
# Compute capital gain
# ************************************

tot_gain = 0
curr_value = 0

for stock in portfolio:
    print(f'{stock["name"]:5s}: # Shares = {stock["shares"]:5d},\
 buy price = {stock["price"]:5.2f} curr price = {prices[stock["name"]]:6.2f}\
 gain = {stock["shares"]*(prices[stock["name"]] - stock["price"]):>8.2f}')
    tot_gain += stock["shares"]*(prices[stock["name"]] - stock["price"])
    curr_value += stock["shares"]*prices[stock["name"]]

print()
print(f'Current portfolio value = {curr_value:10.2f}')
print(f'Total gain = {tot_gain:10.2f}')
