const util = require("util");
const addr1 = "foo";
const addr2 = "bar";
const fee = "fee";
const percentage = 0.005;

function dbg(obj) {
  console.log(util.inspect(obj, false, null, true /* enable colors */))
}

async function get_balance(account) {
  const response = await fetch(`http://127.0.0.1:8080/balance/${account}`);
  return response.json();
}

async function deposit(account, amount, asset) {
  const response = (await fetch("http://127.0.0.1:8080/deposit", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      memo: "deposit",
      account,
      amount: amount.toString(),
      asset,
      status: 'pending',
    })
  }));
  return response.json();
}

async function trade(amount, asset, from, amount_to, asset_to, to) {
  const response = (await fetch("http://127.0.0.1:8080/tx", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      memo: "trade",
      debit: [
        {
          account: from,
          amount: amount.toString(),
          asset
        },
        {
          account: to,
          amount: amount_to.toString(),
          asset: asset_to,
        }
      ],
      credit: [
        {
          account: to,
          amount: (amount * (1 - percentage)).toString(),
          asset
        },
        {
          account: from,
          amount: amount_to.toString(),
          asset: asset_to
        },
        {
          account: fee,
          amount: (amount * percentage).toString(),
          asset
        }
      ],
      status: 'pending',
      asset,
    })
  }));
  return response.json();
}

async function change_status(id, s_status) {
  const response = (await fetch(`http://127.0.0.1:8080/${id}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      status: s_status,
      memo: `change status to ${s_status}`,
    })
  }));
  return response.json();
}

async function test() {
  let d = (await deposit(addr1, 1.5, "BTC/8"));
  dbg(d);
  dbg(await change_status(d.id, 'settled'));
  d = (await deposit(addr2, 1000000, "USD/4"));
  dbg(await change_status(d.id, 'settled'));

  const t = await trade(1, "BTC/8", addr1, 26751.11, "USD/4", addr2);
  dbg(t);
  dbg(await change_status(t.id, 'processing',));
  dbg(await change_status(t.id, 'settled'));
  dbg(await get_balance(addr1));
  dbg(await get_balance(addr2));
  dbg(await get_balance(fee));
}

test()