#!/usr/bin/env python3
# Copyright (c) 2022 The Bitcoin Unlimited developers
"""
Test the `token.nft.list` RPC call
"""

import asyncio
from test_framework.util import assert_equal
from test_framework.electrumutil import (
    ElectrumTestFramework,
)
from test_framework.environment import on_bch, on_nex
from test_framework.electrumconnection import ElectrumConnection


class ElectrumTokenNFTList(ElectrumTestFramework):
    async def run_test(self):
        # This test users nexad wallet to create and send tokens.
        # Mine and mature some coins.
        n = self.nodes[0]
        n.generate(120)

        cli = ElectrumConnection()
        await cli.connect()
        await self.sync_height(cli)
        try:
            await self.test_list(n, cli)
        finally:
            cli.disconnect()

    async def test_list(self, n, cli):
        baton_token_amount = 1 if on_nex() else 0
        token_id, txid = await self.create_token(
            to_addr=n.getnewaddress(),
            mint_amount=baton_token_amount,
            bch_can_mint_nft=True,
        )
        await self.wait_for_mempool_tx(cli, txid)

        res = await cli.call("token.nft.list", token_id)
        assert "cursor" in res
        if on_nex():
            assert_equal(0, len(res["nft"]))
        elif on_bch():
            # minting utxo is an NFT
            assert_equal(1, len(res["nft"]))
        else:
            raise Exception("unknown node")

        nft1 = self.create_nft(token_id, n.getnewaddress(), 255)
        nft2 = self.create_nft(token_id, n.getnewaddress(), 24)
        nft3 = self.create_nft(token_id, n.getnewaddress(), 3)

        await self.sync_mempool(cli)
        res = await cli.call("token.nft.list", token_id)
        if on_bch():
            # The minting baton is also a NFT
            assert_equal(4, len(res["nft"]))
            res_ids = list(map(lambda x: x["commitment"], res["nft"]))
        elif on_nex():
            assert_equal(3, len(res["nft"]))
            res_ids = list(map(lambda x: x["token_id_hex"], res["nft"]))
        else:
            raise NotImplementedError()

        assert await self.decode_groupid(cli, nft1) in res_ids
        assert await self.decode_groupid(cli, nft2) in res_ids
        assert await self.decode_groupid(cli, nft3) in res_ids


if __name__ == "__main__":
    asyncio.run(ElectrumTokenNFTList().main())
