# report.py
#
# Exercise 2.9, 2.10, 2.11 and 2.12

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


# ************************************************
# More improved reading empty lines...
#
#    Add line number of empty line
# ************************************************
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 rowNo, row in enumerate(csv_f):
            print(row)        # row is a list
            try:
               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
            except Exception:
               print(f'*** line {rowNo}: Bad data row: {row}')
    return data


# ************************************************
# Improved reading empty lines:
#
#      Use exception handling
# ************************************************
def read_prices2(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
            try:
               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
            except Exception:
               print(f'*** Bad data row: {row}')
    return data



def read_prices_ORIG(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)


# ************************************
# Print report
# ************************************

headersPrinted = False

for stock in portfolio:
#   print(stock)
#   print(stock.keys())
    name,price,shares = stock.keys()
    if not headersPrinted:
       print(f'{name.title():>10s} {shares.title():>10s}\
 {price.title():>10s} {"Change":>10s}')
       print(f'---------- ---------- ---------- ----------')
       headersPrinted = True

    price_str = '{x:0.2f}'.format(x=prices[stock["name"]])
    price_str = "$" + price_str
    print(f'{stock["name"]:>10s} {stock["shares"]:>10d}\
 {price_str:>10s}\
 {(prices[stock["name"]] - stock["price"]):>10.2f}')

