using Nethereum.Contracts;
using Nethereum.Contracts.Standards.ERC721.ContractDefinition;
using Nethereum.Web3;

namespace Managing.Infrastructure.Evm.Services;

public static class NftService
{
    public static async Task<List<EventLog<TransferEventDTO>>> GetNftEvent(Web3 web3, string owner, string contract)
    {
        try
        {
            // Retrieve transfer event of the contract
            var transferEvent = web3.Eth.GetEvent<TransferEventDTO>(contract);

            // Create IN & OUT filter to filter the return transfers changes
            var transferFilterIn = transferEvent.CreateFilterInput<string, string>(null, owner);
            var transferFilterOut = transferEvent.CreateFilterInput(owner);

            // Retrieve changes based on filter
            var transferInLogs = await transferEvent.GetAllChangesAsync(transferFilterIn);
            var transferOutLogs = await transferEvent.GetAllChangesAsync(transferFilterOut);

            var list = new List<EventLog<TransferEventDTO>>();

            // For each transfer IN, we add the event into the list
            foreach (var ins in transferInLogs)
            {
                list.Add(ins);
            }

            // Remove all transfer OUT of the list because the use might already send the token
            foreach (var ins in transferOutLogs)
            {
                list.Remove(ins);
            }
            return list;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
    }
}
