import http from '@/utils/http';
import _ from 'lodash';
import BigNumber from 'bignumber.js';
import { CoinUnion, CoinSupport, CoinAddress } from '@/types/common';
import { loadCoins, storeCoins } from '@/utils/storage';

export async function getCoins(): Promise<CoinUnion[]> {
  // const coinsCached = loadCoins();
  // if (coinsCached && coinsCached.length) {
  //   return coinsCached;
  // }

  const [
    { ok: sOk, data: sData, msg: sMsg },
    { ok: aOk, data: aData, msg: aMsg },
  ] = await Promise.all([
    http.get<CoinSupport[]>('/fund/depositCoins'),
    http.get<CoinAddress[]>('/fund/queryAddress'),
  ]);

  if (!sOk || !sData) {
    throw Error(sMsg);
  }

  if (!aOk || !aData) {
    throw Error(aMsg);
  }

  const result = sData.map(it => Object.assign(
    it,
    _.find(aData, ['id', it.id]),
  ));
  // storeCoins(result);

  return result;
}

export function calcRate(input: string, rate?: string): string {
  if (!input || !rate) return '';
  return new BigNumber(input).times(rate).decimalPlaces(2).toString();
}
