#!/usr/bin/python3
#Code generated by Nathan Gjerdingen
#For CSCI 2061-70 Python for Programmers (Online)

def writeToDisk(portfolio, data_file):
        
        ##Load data_file into new object to write to 
        write_file = open(data_file, 'w')

        ##Dump portfolio data into new file
        for company_data in portfolio:
                print(company_data, file = write_file, end = '')

        ##Close data_file
        write_file.close()

def addStock(portfolio, data_file):
        
        ##Get stock info
        ticker = str(input('\nTicker: '))
        company_name = str(input('Company name: '))
        shares = str(input('Number of shares: '))
        price = str(input('Purchase price per share: '))

        ##Return a list to append to portfolio
        return([ticker, company_name, shares, price, price])


def deleteStock(portfolio):
        
        ##Have user select which stock to remove
        removed_stock = input('Enter the ticker symbol of the stock to remove:')

        ##Access portfolio to find a stock that matches user input
        company = 0
        for line in portfolio:
                if removed_stock == portfolio[company][0]:
                        del portfolio[company]
                company += 1
        
def loadFile(data_file):
        
        ##Load file of choice into 'write_file' object
        data_file = open(input('Load file: '), 'w')
        data_file.close()

        ##Return the name of our data_file for later use
        return(data_file.name)

def loadPortfolio(portfolio, data_file):
        
        ##Give 'portfolio' list its default companies and company data if empty
        if portfolio == []:
                portfolio = [['MMM', '3M', '100', '74.00', '118.30'],
                             ['MDT', 'Medtronic', '50', '56.10', '48.00'],
                             ['NWAC', 'Northwest Airlines', '100', '67.50', '18.04'],
                             ['SGI', 'Silicon Graphics', '100', '22.25', '2.25']]

        ##Return portfolio for later use
        return(portfolio)

def report(portfolio, data_file):
        
        ##If file hasn't been created yet, prompt the user
        if data_file == '': loadFile(data_file)
                
        ##Call 'writeToDisk' to write your portfolio to disk
        writeToDisk(portfolio, data_file)
        
        ##Input how you want the portfolio to be displayed
        count = 0
        total_value = 0
        total_gl = 0
        display = input('Sort output on (N)ame, or (V)alue? ')
        
        ##Print our portfolio to the screen.
        print('\nCompany                   Shares   Pur.  Latest   Value     G/L')
        print('=================================================================')
        for rows in portfolio:
                print('{:<25}'.format(portfolio[count][1] + ' (' + portfolio[count][0] + ')') +
                      '{:>6}'.format(portfolio[count][2]) +
                      '{:>8}'.format(portfolio[count][3]) +
                      '{:>8}'.format(portfolio[count][4]) +
                      '{:>8}'.format(float(portfolio[count][2]) * float(portfolio[count][4])) +
                      '{:>9}'.format('{:.2%}'.format((float(portfolio[count][4]) - float(portfolio[count][3])) /
                                                     (float(portfolio[count][2]) * float(portfolio[count][3])) * 100)))
                total_value += (float(portfolio[count][2]) * float(portfolio[count][4]))
                total_gl += ((float(portfolio[count][4]) - float(portfolio[count][3])) /
                             (float(portfolio[count][2]) * float(portfolio[count][3])) * 100)
                count += 1

        print('{:>65}'.format('---------------'))
        print('{:>55}'.format(int(total_value)) + '{:>10}'.format('{:.2%}'.format(total_gl/4)))

def updatePrice(portfolio):
        
        ##Have user select which stock to remove
        print('Update stock prices (<Return> to keep current value)...\n')

        ##Access portfolio to find a stock that matches user input
        company = 0
        for line in portfolio:
                new_data = input(portfolio[company][0] + ':')
                if new_data == '': pass
                else: portfolio[company][3] = new_data
                company += 1

        ##Return new portfolio prices for later use
        return(portfolio)

def main():
        
        ##Declare all needed variables
        action = ''
        portfolio = []
        data_file = ''
        
        ##Loop the menu prompt 
        while action != 'q':
                action = input('\n(A)dd/(D)elete stocks,(L)oad file,(U)pdate prices, (R)eport, or (Q)uit? ')

                ##If else statement controls the methods of the program
                if action=='a':
                        print('Add a stock to your portfolio...')
                        portfolio.append(addStock(portfolio, data_file))
                elif action=='d':
                        deleteStock(portfolio)
                elif action=='l':
                        ##If you haven't created a file yet, it will prompt you to make one
                        if data_file == '':
                                data_file = loadFile(data_file)

                        ##loadPortfolio is called and stored into portfolio
                        portfolio = loadPortfolio(portfolio, data_file)                       
                elif action=='u':
                        portfolio = updatePrice(portfolio)
                elif action=='r':
                        report(portfolio, data_file)
                elif action=='q':
                        last_action = input('Save ' + data_file + ' (y/n)? ')
                        if last_action == 'y': print('Bye.')
                        else: print('Bye.')
                else: print('Invalid selection, try again: \n\n')

if __name__ == "__main__": main()
