'use strict';

const Grid = require('term-grid');

module.exports = tools => {
  /**
   * Format a number for nice table outputs.
   *
   * @param num {String|Number}
   *   Convert a value to its number representation with 2 decimal places.
   *
   * @returns {String}
   *   The formatted number.
   */
  const format = num => Number(num).toFixed(2);

  /**
   * Wrap the given number in a tools.chalk color
   *
   * @param num {Number}
   *   The Number to wrap, based upon is +/- value.
   *
   * @returns {String}
   *   The color formatted number.
   */
  const color = num =>
    num < 0 ? tools.chalk.black.bgRed(num) : tools.chalk.black.bgGreen(num);

  tools.getPortfolio().then(portfolio => {
    Promise.all(Object.keys(portfolio.stocks).map(tools.getSymbol))
      .then(data => {
        // Build the data grid for all the stocks in the portfolio.
        const output = [
          ['Symbol', 'Name', 'Price', 'Shares', 'Cost', 'Total $', 'G/L $'].map(
            label => tools.chalk.underline.bold(label)
          )
        ];
        let grandTotal = 0;
        let grandCost = 0;

        data.forEach(({ symbol, name, currentPrice }) => {
          let total = 0;
          let cost = 0;
          let count = 0;
          const orders = portfolio.stocks[symbol].orders;
          orders.forEach(({ shares, price }) => {
            total += shares * currentPrice;
            cost += shares * price;
            count += shares;
          });

          // Update the global amounts.
          grandTotal += total;
          grandCost += cost;

          // Build the data grid row.
          output.push([
            symbol,
            name,
            format(currentPrice),
            count,
            format(cost),
            format(total),
            color(format(total - cost))
          ]);
        });

        // Add the Money/running total to the data grid.
        const cash =
          portfolio.hasOwnProperty('money') &&
          portfolio.money.hasOwnProperty('usd') &&
          portfolio.money.usd
            ? Number(portfolio.money.usd)
            : 0;
        output.push(['', '', '', '', '', '', '']);
        output.push(['Cash', '', '', '', '', '', format(cash)]);
        output.push([
          'Total',
          '',
          '',
          '',
          format(grandCost),
          format(grandTotal),
          color(format(grandTotal - grandCost))
        ]);

        // Build and render the data grid before exiting.
        let grid = new Grid(output);
        grid.setAlign([
          'left',
          'left',
          'right',
          'right',
          'right',
          'right',
          'right'
        ]);
        grid.draw();
      })
      .catch(err => {
        // Return a nice message if the portfolio is empty.
        if (Object.keys(portfolio.stocks).length === 0) {
          return tools.cli.error('No stocks configured for display.');
        }

        return tools.error(err, true);
      });
  });
};

@@ -1847,273 +1847,8 @@
     
-// Add the Money/running total to the data grid.%0A        const cash =%0A          portfolio.hasOwnProperty('money') &&%0A          portfolio.money.hasOwnProperty('usd') &&%0A          portfolio.money.usd%0A            ? Number(portfolio.money.usd)%0A            : 0;%0A        
 outp
@@ -1855,16 +1855,27 @@
 ut.push(
+%0A          
 %5B'', '',
@@ -1894,18 +1894,17 @@
  '', ''%5D
-);
+,
 %0A       
@@ -1908,87 +1908,14 @@
     
-output.push(%5B'Cash', '', '', '', '', '', format(cash)%5D);%0A        output.push(%5B%0A
+  %5B%0A  
     
@@ -1931,36 +1931,40 @@
 tal',%0A          
+ 
+ 
 '',%0A
+  
           '',%0A  
@@ -1963,32 +1963,34 @@
   '',%0A          
+  
 '',%0A          fo
@@ -1979,32 +1979,34 @@
   '',%0A          
+ 
+ 
 format(grandCost
@@ -2004,24 +2004,26 @@
 grandCost),%0A
+  
           fo
@@ -2036,24 +2036,26 @@
 randTotal),%0A
+  
           co
@@ -2098,17 +2098,28 @@
         
-%5D
+  %5D%0A        
 );%0A%0A    

Remove the cash output from the simplified display.