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,
      cents: amount.toString(),
      tags: ['deposit'],
      asset,
      status: 'pending',
    })
  }));
  return response.json();
}

async function trade(amount, asset, from, amount_to, asset_to, to) {
  const request = {
    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,
  }
  console.log(request)
  const response = (await fetch("http://127.0.0.1:8080/tx", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(request)
  }));
  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 depositAndConfirm(account, amount, asset) {
  let d = (await deposit(account, amount, asset));
  dbg(d);
  dbg(await change_status(d._rev, 'settled'));
}

async function test() {
  /* */
  await depositAndConfirm(addr1, 111512312, "BTC/8");
  await depositAndConfirm(addr2, 300512312, "USD/4");
  /* */
  let t = await trade(0.01, "BTC/8", addr1, 26751.11, "USD/4", addr2);
  dbg(t);
  t = await change_status(t._rev, 'processing',);
  dbg(t)
  console.log('set settle')
  dbg(await change_status(t._rev, 'settled'));
  dbg(await get_balance(addr1));
  dbg(await get_balance(addr2));
  dbg(await get_balance(fee));
}

test()