/* eslint no-console:"off" */

/**
 * This script demonstrates how to do transfer asset
 * Since exchange tx requires multi-parti-signature, it's complicated
 * Run script with: `DEBUG=@ocap/client node examples/transfer_asset.js`
 */

const { fromRandom } = require('@ocap/wallet');
const GraphQLClient = require('../lib/node');

const endpoint = process.env.OCAP_API_HOST || 'http://127.0.0.1:4000'; // testnet

const client = new GraphQLClient(`${endpoint}/api`);
const sleep = (timeout) =>
  new Promise((resolve) => {
    setTimeout(resolve, timeout);
  });

(async () => {
  try {
    const sender = fromRandom();
    const receiver = fromRandom();
    console.log({
      sender: sender.address,
      receiver: receiver.address,
    });

    // 1. declare sender
    let hash = await client.declare({ moniker: 'sender', wallet: sender });
    console.log('view sender account', `${endpoint}/explorer/accounts/${sender.address}`);
    console.log('view sender tx', `${endpoint}/explorer/txs/${hash}`);

    // 2. declare receiver
    hash = await client.declare({ moniker: 'receiver', wallet: receiver });
    console.log('view receiver account', `${endpoint}/explorer/accounts/${receiver.address}`);
    console.log('view receiver tx', `${endpoint}/explorer/txs/${hash}`);
    await sleep(3000);

    // 3. create asset for sender
    let assetAddress;
    [hash, assetAddress] = await client.createAsset({
      moniker: 'asset_to_be_transferred',
      data: {
        typeUrl: 'json',
        value: {
          value: 'something valuable',
          sn: Math.random(),
        },
      },
      wallet: sender,
    });
    console.log('created asset', `${endpoint}/explorer/assets/${assetAddress}`);
    console.log('created asset tx', `${endpoint}/explorer/txs/${hash}`);

    // 4. transfer asset to receiver
    await sleep(3000);
    hash = await client.transfer({
      to: receiver.address,
      assets: [assetAddress],
      memo: 'this is the transfer note',
      wallet: sender,
    });
    console.log('view transfer tx', `${endpoint}/explorer/txs/${hash}`);
  } catch (err) {
    console.error(err);
    console.log(JSON.stringify(err.errors));
  }
})();
