'use strict';

import { formatAmount, getPercentCell } from "./SharePrices_Common.js";

/*
function createAccountsTables() {
  function getAccounts() {
    let accounts = [];
    function indexOfAccount(accountName) { return accounts.map(function (item) { return item.accountName; }).indexOf(accountName); };
    function getAccount(accountName) { return accounts[indexOfAccount(accountName)]; };
    function addAccountHolding(instrument, exchangeRate, holding) {
      let a = getAccount(holding.AccountName);
      if (!a) {
        a = { accountName: holding.AccountName, holdings: [], totalCostGBP: 0, totalValueGBP: 0, totalGainGBP: 0, totalCashGBP: 0 };
        accounts.push(a);
      }
      let h = {
        instrumentName: instrument.InstrumentName,
        symbol: instrument.Symbol,
        instrumentType: instrument.InstrumentType,
        currency: instrument.Currency,
        purchaseDate: holding.PurchaseDate,
        purchasePricePerUnit: holding.PurchasePricePerUnit,
        noUnits: holding.NoUnits,
        cost: holding.NoUnits * holding.PurchasePricePerUnit
      }
      //if (exchangeRate) {
      //h.costGBP = h.cost / exchangeRate;
      h.costGBP = holding.BookCostGBP;
      if (instrument.InstrumentType != 'CURRENCY') {
        a.totalCostGBP += holding.BookCostGBP;
      }
      //}
      if (instrument.CurrentPrice) {
        h.currentPrice = instrument.CurrentPrice;
        h.currentValue = holding.NoUnits * instrument.CurrentPrice;
        h.gain = h.currentValue - h.cost;
        if (exchangeRate) {
          h.currentValueGBP = h.currentValue / exchangeRate;
          //h.gainGBP = h.gain / exchangeRate;
          h.gainGBP = h.currentValueGBP - h.costGBP;
          if (instrument.InstrumentType != 'CURRENCY') {
            a.totalGainGBP += h.gainGBP;
            a.totalValueGBP += h.currentValueGBP;
          }
        }
      }
      if (instrument.InstrumentType == 'CURRENCY') {
        //Don't add cash holdings - just add the cash value to the account
        a.totalCashGBP += h.currentValueGBP;
      } else {
        a.holdings.push(h);
      }
    }

    for (let ix = 0; ix < Instruments.Data.length; ix++) {
      let i = Instruments.Data[ix];
      let exchangegRate = Instruments.GetExchangeRate(i.Currency, 'GBP');
      for (let hx = 0; hx < i.Holdings.length; hx++) {
        let h = i.Holdings[hx];
        if (h.SoldDate == null) {
          addAccountHolding(i, exchangegRate, h);
        }
      }
    }

    return accounts;
  }

  let accounts = getAccounts();

  //Sort the accounts array by accountName
  accounts.sort(function (a, b) {
    if (a.accountName < b.accountName) return -1;
    if (a.accountName > b.accountName) return 1;
    return 0;
  });

  //let summaryTable = "<table class='accounts' id='accountsSummaryTable'><thead><tr><th>Account Name</th><th>No. Holdings</th><th>Total Cost (GBP)</th><th>Current Value</th><th>Total Gain</th></tr></thead><tbody>";
  let summaryTable = "<table class='accounts' id='accountsSummaryTable'><thead><tr>" +
    "<th>Account Name</th>" +
    "<th>No. Holdings</th>" +
    "<th>Total Cost (GBP)</th>" +
    "<th>Total Gains (GBP)</th>" +
    "<th>Total Losses (GBP)</th>" +
    "<th>Current Investements Value</th>" +
    "<th>NET Gain</th>" +
    "<th>Cash Balance GBP</th>" +
    "<th>Total Value GBP</th>" +
    "</tr></thead><tbody>";
  let accountsTables = ''
  let tableIDs = ['accountsSummaryTable'];
  let hideEmptyAccounts = $('#hideEmptyAccounts').prop('checked');
  let altRow = 1;
  for (let ax = 0; ax < accounts.length; ax++) {
    let a = accounts[ax];
    let accountGainsGBP = 0;
    let accountLossesGBP = 0;
    let accountValueGBP = 0;
    let profitOrLoss = a.totalGainGBP < 0 ? 'loss' : 'profit';
    if (a.holdings.length > 0) {
      altRow = !altRow;

      accountsTables += '<br>' + a.accountName + '<br>'
      let tableID = 'accountTable' + ax;
      tableIDs.push(tableID);
      accountsTables += '<table class="accounts" id="' + tableID + '">' +
        '<thead><tr>' +
        '<th>Name</th>' +
        '<th>Symbol</th>' +
        '<th>Buy Date</th>' +
        '<th>No Units</th>' +
        '<th>Buy Price</th>' +
        '<th>Current Price</th>' +
        '<th>Book Cost</th>' +
        '<th>Approx Book Cost £</th>' +
        '<th>Current Value</th>' +
        '<th>Current Value £</th>' +
        '<th>Gain</th>' +
        '<th>Gain £</th>' +
        '<th>Gain %</th>' +
        '</tr></thead><tbody>';
      let accountAltRow = 1;
      for (let hx = 0; hx < a.holdings.length; hx++) {
        let h = a.holdings[hx];
        accountAltRow = !accountAltRow;
        let holdingProfitOrLoss = h.gain < 0 ? 'loss' : 'profit';
        let holdingGBPProfitOrLoss = h.gainGBP < 0 ? 'loss' : 'profit';
        if (h.gainGBP > 0) {
          accountGainsGBP += h.gainGBP;
        } else {
          accountLossesGBP += h.gainGBP;
        }
        accountValueGBP += h.currentValueGBP;
        accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
          '<td>' + h.instrumentName + '</td>' +
          '<td>' + h.symbol + '</td>' +
          '<td>' + new Date(h.purchaseDate).yyyymmdd() + '</td>' +
          '<td class="num">' + h.noUnits + '</td>' +
          '<td class="num">' + formatAmount(h.purchasePricePerUnit, h.currency, 2) + '</td>' +
          '<td class="num">' + formatAmount(h.currentPrice, h.currency, 2) + '</td>' +
          '<td class="num">' + (h.currency == 'GBp' ? formatAmount(h.cost / 100, 'GBP', 2) : formatAmount(h.cost, h.currency, 2)) + '</td>' +
          '<td class="num">' + formatAmount(h.costGBP, 'GBP', 2) + '</td>' +
          '<td class="num">' + (h.currency == 'GBp' ? formatAmount(h.currentValue / 100, 'GBP', 2) : formatAmount(h.currentValue, h.currency, 2)) + '</td>' +
          '<td class="num">' + formatAmount(h.currentValueGBP, 'GBP', 2) + '</td>' +
          '<td class="num ' + holdingProfitOrLoss + '">' + formatAmount(h.gain, h.currency, 2) + '</td>' +
          '<td class="num ' + holdingGBPProfitOrLoss + '">' + formatAmount(h.gainGBP, 'GBP', 2) + '</td>' +
          //'<td class="num ' + holdingProfitOrLoss + '">' + ((h.gain / h.cost) * 100).toFixed(1) + '%</td>' +
          '<td class="num ' + holdingGBPProfitOrLoss + '">' + ((h.gainGBP / h.costGBP) * 100).toFixed(1) + '%</td>' +
          '</tr>';
      }
      //Add the Total Gains
      accountAltRow = !accountAltRow;
      accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
        '<td class="num" colspan="11">Total Gains</td>' +
        '<td class="num profit">' + formatAmount(accountGainsGBP, 'GBP', 2) + '</td>' +
        '<td class="num">&nbsp;</td>' +
        '</tr>';
      //Add the Total Losses
      accountAltRow = !accountAltRow;
      accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
        '<td class="num" colspan="11">Total Losses</td>' +
        '<td class="num loss">' + formatAmount(accountLossesGBP, 'GBP', 2) + '</td>' +
        '<td class="num">&nbsp;</td>' +
        '</tr>';
      //Add the NET Gains summary line
      accountAltRow = !accountAltRow;
      accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
        '<td class="num" colspan="9">Account Value:</td>' +
        '<td class="num ' + ((accountGainsGBP + accountLossesGBP) > 0 ? 'profit' : 'loss') + '">' + formatAmount(accountValueGBP, 'GBP', 2) + '</td>' +
        '<td class="num">NET Gain</td>' +
        '<td class="num ' + ((accountGainsGBP + accountLossesGBP) > 0 ? 'profit' : 'loss') + '">' + formatAmount(accountGainsGBP + accountLossesGBP, 'GBP', 2) + '</td>' +
        '<td class="num">&nbsp;</td>' +
        '</tr>';
      accountsTables += '</tbody></table>';
    }

    //Add an entry to the summary table
    if (a.totalValueGBP + a.totalCashGBP > 0 || !hideEmptyAccounts) {
      summaryTable += "<tr" + (altRow ? ' class="altShareRow"' : '') + "><td>" + a.accountName + "</td>" +
        "<td>" + a.holdings.length + "</td>" +
        "<td class='num'>" + formatAmount(a.totalCostGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(accountGainsGBP, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(accountLossesGBP, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(a.totalValueGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num " + profitOrLoss + "'>" + formatAmount(a.totalGainGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(a.totalCashGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(a.totalValueGBP + a.totalCashGBP || 0, 'GBP', 2) + "</td>" +
        "</tr>";
    }
  }
  summaryTable += "</tbody></table>";
  $("#accountsSummaryDiv").html(summaryTable + '<br>' + accountsTables);
}
*/
export function createAccountsTables(Instruments) {
  function getAccounts() {
    let accounts = [];
    function indexOfAccount(accountName) { return accounts.map(function (item) { return item.accountName; }).indexOf(accountName); };
    function getAccount(accountName) { return accounts[indexOfAccount(accountName)]; };
    function addAccountHolding(instrument, exchangeRate, holding) {
      let a = getAccount(holding.AccountName);
      if (!a) {
        a = { accountName: holding.AccountName, holdings: [], totalCostGBP: 0, totalValueGBP: 0, totalGainGBP: 0, totalCashGBP: 0 };
        accounts.push(a);
      }
      let h = {
        instrumentName: instrument.InstrumentName,
        symbol: instrument.Symbol,
        instrumentType: instrument.InstrumentType,
        currency: instrument.Currency,
        purchaseDate: holding.PurchaseDate,
        purchasePricePerUnit: holding.PurchasePricePerUnit,
        noUnits: holding.NoUnits,
        cost: holding.NoUnits * holding.PurchasePricePerUnit
      }
      //if (exchangeRate) {
      //h.costGBP = h.cost / exchangeRate;
      h.costGBP = holding.BookCostGBP;
      if (instrument.InstrumentType != 'CURRENCY') {
        a.totalCostGBP += holding.BookCostGBP;
      }
      //}
      if (instrument.CurrentPrice) {
        h.currentPrice = instrument.CurrentPrice;
        h.currentValue = holding.NoUnits * instrument.CurrentPrice;
        h.gain = h.currentValue - h.cost;
        if (exchangeRate) {
          h.currentValueGBP = h.currentValue / exchangeRate;
          //h.gainGBP = h.gain / exchangeRate;
          h.gainGBP = h.currentValueGBP - h.costGBP;
          if (instrument.InstrumentType != 'CURRENCY') {
            a.totalGainGBP += h.gainGBP;
            a.totalValueGBP += h.currentValueGBP;
          }
        }
      }
      if (instrument.InstrumentType == 'CURRENCY') {
        //Don't add cash holdings - just add the cash value to the account
        a.totalCashGBP += h.currentValueGBP;
      } else {
        a.holdings.push(h);
      }
    }

    for (let ix = 0; ix < Instruments.Data.length; ix++) {
      let i = Instruments.Data[ix];
      let exchangegRate = Instruments.GetExchangeRate(i.Currency, 'GBP');
      for (let hx = 0; hx < i.Holdings.length; hx++) {
        let h = i.Holdings[hx];
        if (h.SoldDate == null) {
          addAccountHolding(i, exchangegRate, h);
        }
      }
    }

    return accounts;
  }

  let accounts = getAccounts();

  //Sort the accounts array by accountName
  accounts.sort(function (a, b) {
    if (a.accountName < b.accountName) return -1;
    if (a.accountName > b.accountName) return 1;
    return 0;
  });

  //let summaryTable = "<table class='accounts' id='accountsSummaryTable'><thead><tr><th>Account Name</th><th>No. Holdings</th><th>Total Cost (GBP)</th><th>Current Value</th><th>Total Gain</th></tr></thead><tbody>";
  let summaryTable = "<table class='accounts' id='accountsSummaryTable'><thead><tr>" +
    "<th>Account Name</th>" +
    "<th>No. Holdings</th>" +
    "<th>Total Cost (GBP)</th>" +
    "<th>Total Gains (GBP)</th>" +
    "<th>Total Losses (GBP)</th>" +
    "<th>Current Investements Value</th>" +
    "<th>NET Gain</th>" +
    "<th>Cash Balance GBP</th>" +
    "<th>Total Value GBP</th>" +
    "</tr></thead><tbody>";
  let accountsTables = ''
  let tableIDs = ['accountsSummaryTable'];
  let hideEmptyAccounts = $('#hideEmptyAccounts').prop('checked');
  let altRow = 1;
  for (let ax = 0; ax < accounts.length; ax++) {
    let a = accounts[ax];
    let accountGainsGBP = 0;
    let accountLossesGBP = 0;
    let accountValueGBP = 0;
    let profitOrLoss = a.totalGainGBP < 0 ? 'loss' : 'profit';
    if (a.holdings.length > 0) {
      altRow = !altRow;

      accountsTables += '<br>' + a.accountName + '<br>'
      let tableID = 'accountTable' + ax;
      tableIDs.push(tableID);
      accountsTables += '<table class="accounts" id="' + tableID + '">' +
        '<thead><tr>' +
        '<th>Name</th>' +
        '<th>Symbol</th>' +
        '<th>Buy Date</th>' +
        '<th>No Units</th>' +
        '<th>Buy Price</th>' +
        '<th>Current Price</th>' +
        '<th>Book Cost</th>' +
        '<th>Approx Book Cost £</th>' +
        '<th>Current Value</th>' +
        '<th>Current Value £</th>' +
        '<th>Gain</th>' +
        '<th>Gain £</th>' +
        '<th>Gain %</th>' +
        '</tr></thead><tbody>';
      let accountAltRow = 1;
      for (let hx = 0; hx < a.holdings.length; hx++) {
        let h = a.holdings[hx];
        accountAltRow = !accountAltRow;
        let holdingProfitOrLoss = h.gain < 0 ? 'loss' : 'profit';
        let holdingGBPProfitOrLoss = h.gainGBP < 0 ? 'loss' : 'profit';
        if (h.gainGBP > 0) {
          accountGainsGBP += h.gainGBP;
        } else {
          accountLossesGBP += h.gainGBP;
        }
        accountValueGBP += h.currentValueGBP;
        accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
          '<td>' + h.instrumentName + '</td>' +
          '<td>' + h.symbol + '</td>' +
          '<td>' + new Date(h.purchaseDate).yyyymmdd() + '</td>' +
          '<td class="num">' + h.noUnits + '</td>' +
          '<td class="num">' + formatAmount(h.purchasePricePerUnit, h.currency, 2) + '</td>' +
          '<td class="num">' + formatAmount(h.currentPrice, h.currency, 2) + '</td>' +
          '<td class="num">' + (h.currency == 'GBp' ? formatAmount(h.cost / 100, 'GBP', 2) : formatAmount(h.cost, h.currency, 2)) + '</td>' +
          '<td class="num">' + formatAmount(h.costGBP, 'GBP', 2) + '</td>' +
          '<td class="num">' + (h.currency == 'GBp' ? formatAmount(h.currentValue / 100, 'GBP', 2) : formatAmount(h.currentValue, h.currency, 2)) + '</td>' +
          '<td class="num">' + formatAmount(h.currentValueGBP, 'GBP', 2) + '</td>' +
          '<td class="num ' + holdingProfitOrLoss + '">' + formatAmount(h.gain, h.currency, 2) + '</td>' +
          '<td class="num ' + holdingGBPProfitOrLoss + '">' + formatAmount(h.gainGBP, 'GBP', 2) + '</td>' +
          //'<td class="num ' + holdingProfitOrLoss + '">' + ((h.gain / h.cost) * 100).toFixed(1) + '%</td>' +
          '<td class="num ' + holdingGBPProfitOrLoss + '">' + ((h.gainGBP / h.costGBP) * 100).toFixed(1) + '%</td>' +
          '</tr>';
      }
      //Add the Total Gains
      accountAltRow = !accountAltRow;
      accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
        '<td class="num" colspan="11">Total Gains</td>' +
        '<td class="num profit">' + formatAmount(accountGainsGBP, 'GBP', 2) + '</td>' +
        '<td class="num">&nbsp;</td>' +
        '</tr>';
      //Add the Total Losses
      accountAltRow = !accountAltRow;
      accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
        '<td class="num" colspan="11">Total Losses</td>' +
        '<td class="num loss">' + formatAmount(accountLossesGBP, 'GBP', 2) + '</td>' +
        '<td class="num">&nbsp;</td>' +
        '</tr>';
      //Add the NET Gains summary line
      accountAltRow = !accountAltRow;
      accountsTables += '<tr' + (accountAltRow ? ' class="altShareRow"' : '') + '>' +
        '<td class="num" colspan="9">Account Value:</td>' +
        '<td class="num ' + ((accountGainsGBP + accountLossesGBP) > 0 ? 'profit' : 'loss') + '">' + formatAmount(accountValueGBP, 'GBP', 2) + '</td>' +
        '<td class="num">NET Gain</td>' +
        '<td class="num ' + ((accountGainsGBP + accountLossesGBP) > 0 ? 'profit' : 'loss') + '">' + formatAmount(accountGainsGBP + accountLossesGBP, 'GBP', 2) + '</td>' +
        '<td class="num">&nbsp;</td>' +
        '</tr>';
      accountsTables += '</tbody></table>';
    }

    //Add an entry to the summary table
    if (a.totalValueGBP + a.totalCashGBP > 0 || !hideEmptyAccounts) {
      summaryTable += "<tr" + (altRow ? ' class="altShareRow"' : '') + "><td>" + a.accountName + "</td>" +
        "<td>" + a.holdings.length + "</td>" +
        "<td class='num'>" + formatAmount(a.totalCostGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(accountGainsGBP, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(accountLossesGBP, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(a.totalValueGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num " + profitOrLoss + "'>" + formatAmount(a.totalGainGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(a.totalCashGBP || 0, 'GBP', 2) + "</td>" +
        "<td class='num'>" + formatAmount(a.totalValueGBP + a.totalCashGBP || 0, 'GBP', 2) + "</td>" +
        "</tr>";
    }
  }
  summaryTable += "</tbody></table>";
  $("#accountsSummaryDiv").html(summaryTable + '<br>' + accountsTables);
}
