using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading.Tasks;
using Knoks.Core.Logic.Interfaces;
using Nethereum.Contracts;
using Nethereum.Hex.HexTypes;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Util;
using Nethereum.Web3;
using Newtonsoft.Json;

namespace Knoks.TokenContractTracking
{
    public class TokenContractService : ITokenContractService
    {
        private Contract _contract;
        private Web3 _web3;

        public TokenContractService(Web3 web3, string contractAddress, string contractAbi)
        {
            if (web3 == null) throw new ArgumentNullException(nameof(web3));
            if (contractAddress == null) throw new ArgumentNullException(nameof(contractAddress));
            if (contractAbi == null) throw new ArgumentNullException(nameof(contractAbi));

            _contract = web3.Eth.GetContract(contractAbi, contractAddress);
            _web3 = web3;
        }

        public async Task<List<EventLog<TransferEventDto>>> GetTransferEvents(ulong startingBlockNumber)
        {
            BlockParameter fromBlock = new BlockParameter(startingBlockNumber);
            BlockParameter toBlock = BlockParameter.CreateLatest();

            var eventWrapper = GetEvent("Transfer");
            var filterInput = eventWrapper.CreateFilterInput(fromBlock, toBlock);
            return await eventWrapper.GetAllChanges<TransferEventDto>(filterInput);
        }

        public Event GetEvent(string eventName)
        {
            return _contract.GetEvent(eventName);
        }

        //public async Task<TransactionInput> CreateWithdrawTransaction(string fromAddress, string toAddress, decimal amountEth)
        //{
        //    BigInteger amountWei = UnitConversion.Convert.ToWei(amountEth);

        //   TransactionInput tx = new TransactionInput(null, _contract.Address, fromAddress, new HexBigInteger(400000),
        //        new HexBigInteger(21000), new HexBigInteger(amountWei));

        //    var txCount = await _web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(args.SenderAddress);

        //    string parametersJson = JsonConvert.SerializeObject(new { args.RepayAmountEth });

        //    var result = new TenderCreateTransactionResult
        //    {
        //        From = args.SenderAddress,
        //        Gas = new HexBigInteger(400000),
        //        GasPrice = new HexBigInteger(21000),
        //        Nonce = txCount,
        //        To = tender.TenderContractAddress,
        //        Value = new HexBigInteger(amountWei)
        //    };

        //    return result;
        //}
    }
}