'use strict';

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

export async function updateLedgerTable(instruments, vars) {
  const noColumns = 15;
  
  function createLedgerTable() {
    let table = $('#ledgerTable');
    //if (table.length == 0) {
      let tblDef = '<table id="ledgerTable" class="ledger">' +
        '<thead>' + getHeaderRow() + '</thead>' +
        '<tbody></tbody>' +
        '</table>';
      $('#ledgerDiv').html(tblDef);
    //}
  }
  function getHeaderRow() {
    return '<tr>' +
      '<th>Trade DT</th>' +
      '<th>Tax Bucket</th>' +
      '<th>Account</th>' +
      '<th>Symbol</th>' +
      '<th>Instrument Name</th>' +
      //'<th>Instrument Currency</th>' +
      '<th>Action<br/>Type</th>' +
      //'<th>No Units</th>' +
      //'<th>Price Per Unit GBP</th>' +
      '<th>Units</th>' +
      '<th>Trade<br/>Value</th>' +
      '<th>New Pool<br/>Total Units</th>' +
      '<th>New Pool<br/>Base Cost</th>' +
      '<th>Realised<br/>Gain</th>' +
      '<th>Is Final<br/>Position</th>' +
      '<th>Notes</th>' +
      '</tr>'
  }
  function getContentRow(row) {
    let rowID = 'ledgerRow_' + row.TradeLedgerID.toString();

    return '<tr id="' + rowID + '" class="ledgerRow">' +
      '<td>' + (new Date(row.TradeDT)).yyyymmddhhmm() + '</td>' +
      '<td>' + row.TaxBucket + '</td>' +
      '<td>' + row.AccountName + '</td>' +
      '<td>' + row.Symbol + '</td>' +
      '<td>' + row.InstrumentName + '</td>' +
      //'<td>' + row.InstrumentCurrency + '</td>' +
      '<td>' + row.ActionType + '</td>' +
      //'<td class="num">' + row.NoUnits.autoScale() + '</td>' +
      //'<td class="num">' + formatAmount(row.PricePerUnitGBP, 'GBP', 2) + '</td>' +
      '<td class="num">' + row.NoUnits.autoScale() + ' @ ' + formatAmount(row.PricePerUnitGBP, 'GBP', 2) + '</td>' +
      '<td class="num">' + formatAmount(row.TradeValueGBP, 'GBP', 2) + '</td>' +
      '<td class="num">' + row.NewPoolTotalUnits.autoScale() + '</td>' +
      '<td class="num">' + formatAmount(row.NewPoolBaseCostGBP, 'GBP', 2) + '</td>' +
      '<td class="num">' + formatAmount(row.RealisedGainGBP, 'GBP', 2) + '</td>' +
      '<td class="num">' + row.IsFinalPosition.toString() + '</td>' +
      '<td>' + (row.Notes == null ? '' : row.Notes) + '</td>' +
      '</tr>'
  }

  //Fetch the ledger data
  let ledger = {};
  try {
    ledger = await $.ajax({
      type: "POST",
      contentType: "application/json",
      url: "SharePrices.aspx/GetTradeHistory"
    });
  }
  catch (error) {
    console.error({ MSG: "Error getting trade history", Error: error });
  }

  createLedgerTable();

  //Create the ledger table rows
  for (let rowNo = 0; rowNo < ledger.length; rowNo++) {
    let r = ledger[rowNo];
    let newContent = getContentRow(r);
    $("#ledgerTable tbody").append(newContent);
  }

  //Add the tableSorter filter widget
  let $table = $("#ledgerTable").tablesorter({
    //theme: 'blue',
    // this is the default setting
    //cssChildRow: "tablesorter-childRow",

    // initialize zebra and filter widgets
    widgets: ["zebra", "filter", "stickyHeaders"],

    widgetOptions: {
      // output default: '{page}/{totalPages}'
      // possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
      //pager_output: '{startRow} - {endRow} / {filteredRows} ({totalRows})',
      //pager_removeRows: false,

      // include child row content while filtering, if true
      //filter_childRows: true,
      // class name applied to filter row and each input
      /*filter_cssFilter: 'tablesorter-filter',

      filter_filteredRow: 'filtered',

      // search from beginning
      filter_startsWith: false,
      // Set this option to false to make the searches case sensitive
      filter_ignoreCase: true,
      */
      stickyHeaders_attachTo: '#ledgerDiv',
      //stickyHeaders_zIndex: 2,
      zebra: [ 'odd', 'even']
    }

  });

}
