/**
 * @fileOverview computed values that are used in transaction UI components.
 */

import { extendObservable } from 'mobx';
import { toAmountLabel, toAmount, toCaps } from '../helper';

const ComputedPool = store => {
  extendObservable(store, {
    get computedPools() {
      const { pools, settings } = store;
      const t = pools ? pools.slice() : [];
      store.poolBalance = 0;
      const all = [].concat(t);
      //all.sort((a, b) => b.date.getTime() - a.date.getTime());
      all.sort((a, b) => b.amount - a.amount);
      all.forEach((t, i) => {
        store.poolBalance =
          store.poolBalance + parseInt(t.quoteFiat * t.amount);
        t.key = String(i);
        t.idName = t.id + ':BITS:MSM1 | ' + t.title;
        t.typeLabel = toCaps(t.type);
        t.statusLabel = toCaps(t.status);
        t.merchantLabel = t.title;
        t.quoteFiat = parseFloat(
          toAmount(parseInt(parseFloat(t.quote) * Math.pow(10, 6)), settings)
        );
        t.dateLabel = t.date.toLocaleDateString();
        t.dateTimeLabel = t.date.toLocaleString();
        t.quoteLabel = toAmountLabel(
          parseInt(parseFloat(t.quote) * Math.pow(10, 6)),
          settings
        );
        t.raised = toAmountLabel(0, settings);
        if (Number.isInteger(t.confirmations)) {
          t.confirmationsLabel = t.confirmations.toString();
        }
      });
      return all.slice(0, 100);
    },
    get poolStatus() {
      const {
        poolBalanceOpenSatoshis: opened,
        poolBalanceInactiveSatoshis: inactive,
        poolBalancePendingSatoshis: pending,
      } = store;
      return opened
        ? 'success'
        : inactive
        ? 'inactive'
        : pending
        ? 'info'
        : 'error';
    },
    get poolBalanceOpenSatoshis() {
      return (store.channels || [])
        .filter(c => c.active)
        .map(c => c.localBalance + c.commitFee)
        .reduce((a, b) => a + b, 0);
    },
    get poolBalanceLabel() {
      var { poolBalance, settings } = store;
      if (isNaN(poolBalance) || poolBalance == undefined) poolBalance = 0;
      console.log(poolBalance);
      return toAmountLabel(poolBalance, settings);
    },
    get poolBalanceOpenLabel() {
      const { channelBalanceOpenSatoshis, settings } = store;
      return toAmountLabel(channelBalanceOpenSatoshis, settings);
    },
    get poolBalancePendingLabel() {
      const { channelBalanceOpenSatoshis, settings } = store;
      return toAmountLabel(channelBalanceOpenSatoshis, settings);
    },
    get poolBalanceInactiveLabel() {
      const { channelBalanceOpenSatoshis, settings } = store;
      return toAmountLabel(channelBalanceOpenSatoshis, settings);
    },
    get poolBalanceClosingLabel() {
      const { channelBalanceOpenSatoshis, settings } = store;
      return toAmountLabel(channelBalanceOpenSatoshis, settings);
    },
  });
};

export default ComputedPool;
