import { BigNumber } from '@polymathnetwork/polymesh-sdk';
import { ApiQueueItem } from '../ui/definition';

export const calcIndividualTxCost = async (
  transaction: ApiQueueItem<any>,
  userAddress: string
) => {
  let cost = new BigNumber(0);

  try {
    const dispatchInfo = await transaction
      .method(...transaction.params)
      .paymentInfo(userAddress);
    cost = new BigNumber(dispatchInfo.partialFee.toString()).div(
      new BigNumber(1000000)
    );
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error(
      'Error when calculating tx cost for transaction',
      transaction
    );
  }

  return cost;
};

export const calcTxCost = async (
  transactions: any = [],
  userAddress: string
) => {
  const costs = await Promise.all(
    transactions.map((tx: ApiQueueItem<any>) =>
      calcIndividualTxCost(tx, userAddress)
    )
  );

  return costs.reduce(
    (totalCost: BigNumber, current: any) => totalCost.plus(current),
    new BigNumber(0)
  );
};
