import http from '@/utils/http';
import _ from 'lodash';
import BigNumber from 'bignumber.js';
import { CoinDrawn, FundBasic } from '@/types/common';
import { encryptPwd } from '@/utils/transform';

export async function getCoins(): Promise<CoinDrawn[]> {
  const { ok, msg, data } = await  http.get<CoinDrawn[]>('/fund/withdrawCoins');

  if (!ok || !data) {
    throw Error(msg);
  }

  return data;
}

export async function withdraw(
  coin: CoinDrawn,
  targetAddress: string,
  amount: string,
  password: string,
): Promise<void> {
  const { ok, msg } = await http.post('/fund/withdraw', {
    coinId: coin.id,
    targetAddress,
    amount,
    password: encryptPwd(password),
  });
  if (ok) return
  throw Error(msg);
}

export function retrieveBalance(basic?: FundBasic, coin?: CoinDrawn): string {
  if (!basic || !coin) return '';
  return (basic as any)[coin.label.toLocaleLowerCase()]
}

export function calcFee(coin: CoinDrawn, input: string): { fee: string, actual: string } {
  const fail = { fee: '', actual: '' };
  if (!coin || !input) return fail;
  const i = new BigNumber(input);
  const f = new BigNumber(coin.fee);
  if (i.isNaN() || f.isNaN()) return fail;
  const fee = i.times(f);
  return {
    fee: fee.decimalPlaces(2).toString(),
    actual: i.minus(fee).decimalPlaces(2).toString(),
  };
}
