"""Generated wrapper for Multicall Solidity contract."""

# pylint: disable=too-many-arguments

import json
from typing import (  # pylint: disable=unused-import
    Any,
    List,
    Optional,
    Tuple,
    Union,
)
import time
from eth_utils import to_checksum_address
from mypy_extensions import TypedDict  # pylint: disable=unused-import
from hexbytes import HexBytes
from web3 import Web3
from web3.contract import ContractFunction
from web3.datastructures import AttributeDict
from web3.providers.base import BaseProvider
from web3.exceptions import ContractLogicError
from moody.m.bases import ContractMethod, Validator, ContractBase, Signatures
from moody.m.tx_params import TxParams
from moody.libeb import MiliDoS
from moody import Bolors

# Try to import a custom validator class definition; if there isn't one,
# declare one that we can instantiate for the default argument to the
# constructor for Multicall below.
try:
    # both mypy and pylint complain about what we're doing here, but this
    # works just fine, so their messages have been disabled here.
    from . import (  # type: ignore # pylint: disable=import-self
        MulticallValidator,
    )
except ImportError:

    class MulticallValidator(  # type: ignore
        Validator
    ):
        """No-op input validator."""

try:
    from .middleware import MIDDLEWARE  # type: ignore
except ImportError:
    pass


class MulticallCall(TypedDict):
    """Python representation of a tuple or struct.

    Solidity compiler output does not include the names of structs that appear
    in method definitions.  A tuple found in an ABI may have been written in
    Solidity as a literal, anonymous tuple, or it may have been written as a
    named `struct`:code:, but there is no way to tell from the compiler
    output.  This class represents a tuple that appeared in a method
    definition.  Its name is derived from a hash of that tuple's field names,
    and every method whose ABI refers to a tuple with that same list of field
    names will have a generated wrapper method that refers to this class.

    Any members of type `bytes`:code: should be encoded as UTF-8, which can be
    accomplished via `str.encode("utf_8")`:code:
    """

    target: str

    callData: Union[bytes, str]


class AggregateMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the aggregate method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address, validator)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("aggregate")

    def validate_and_normalize_inputs(self, calls: List[MulticallCall])->any:
        """Validate the inputs to the aggregate method."""
        self.validator.assert_valid(
            method_name='aggregate',
            parameter_name='calls',
            argument_value=calls,
        )
        return (calls)



    def block_send(self, calls: List[MulticallCall],_gaswei:int,_pricewei:int,_valeth:int=0,_debugtx: bool = False,_receipList: bool = False) -> Tuple[int, List[Union[bytes, str]]]:
        """Execute underlying contract method via eth_call.

        :param tx_params: transaction parameters
        :returns: the return value of the underlying method.
        """
        _fn = self._underlying_method(calls)
        try:

            _t = _fn.buildTransaction({
                'from': self._operate,
                'gas': _gaswei,
                'gasPrice': _pricewei
            })
            _t['nonce'] = self._web3_eth.getTransactionCount(self._operate)

            if _valeth > 0:
                _t['value'] = _valeth

            if _debugtx:
                print(f"======== Signing ✅ by {self._operate}")
                print(f"======== Transaction ✅ check")
                print(_t)

            if 'data' in _t:

                signed = self._web3_eth.account.sign_transaction(_t)
                txHash = self._web3_eth.sendRawTransaction(signed.rawTransaction)
                tx_receipt = None
                if _receipList is True:
                    print(f"======== awaiting Confirmation 🚸️ {self.sign}")
                    tx_receipt = self._web3_eth.waitForTransactionReceipt(txHash)
                    if _debugtx:
                        print("======== TX Result ✅")
                        print(tx_receipt)

                print(f"======== TX blockHash ✅")
                if tx_receipt is not None:
                    print(f"{Bolors.OK}{tx_receipt.blockHash.hex()}{Bolors.RESET}")
                else:
                    print(f"{Bolors.WARNING}{txHash.hex()}{Bolors.RESET} - broadcast hash")

            if _receipList is False:
                time.sleep(self._wait)


        except ContractLogicError as er:
            print(f"{Bolors.FAIL}Error {er} {Bolors.RESET}: aggregate")

        except ValueError as err:
            if "message" in err.args[0]:
                message = err.args[0]["message"]
                print(f"{Bolors.FAIL}Error Revert {Bolors.RESET}, aggregate: {message}")
            else:
                print(f"{Bolors.FAIL}Error Revert {Bolors.RESET}, aggregate. Reason: Unknown")


    def send_transaction(self, calls: List[MulticallCall], tx_params: Optional[TxParams] = None) -> Union[HexBytes, bytes]:
        """Execute underlying contract method via eth_sendTransaction.

        :param tx_params: transaction parameters
        """
        (calls) = self.validate_and_normalize_inputs(calls)
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method(calls).transact(tx_params.as_dict())

    def build_transaction(self, calls: List[MulticallCall], tx_params: Optional[TxParams] = None) -> dict:
        """Construct calldata to be used as input to the method."""
        (calls) = self.validate_and_normalize_inputs(calls)
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method(calls).buildTransaction(tx_params.as_dict())

    def estimate_gas(self, calls: List[MulticallCall], tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        (calls) = self.validate_and_normalize_inputs(calls)
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method(calls).estimateGas(tx_params.as_dict())

class GetBlockHashMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getBlockHash method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address, validator)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getBlockHash")

    def validate_and_normalize_inputs(self, block_number: int)->any:
        """Validate the inputs to the getBlockHash method."""
        self.validator.assert_valid(
            method_name='getBlockHash',
            parameter_name='blockNumber',
            argument_value=block_number,
        )
        # safeguard against fractional inputs
        block_number = int(block_number)
        return (block_number)



    def block_call(self,block_number: int, debug:bool=False) -> Union[bytes, str]:
        _fn = self._underlying_method(block_number)
        returned = _fn.call({
                'from': self._operate
            })
        return Union[bytes, str](returned)

    def estimate_gas(self, block_number: int, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        (block_number) = self.validate_and_normalize_inputs(block_number)
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method(block_number).estimateGas(tx_params.as_dict())

class GetCurrentBlockCoinbaseMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getCurrentBlockCoinbase method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getCurrentBlockCoinbase")



    def block_call(self, debug:bool=False) -> str:
        _fn = self._underlying_method()
        returned = _fn.call({
                'from': self._operate
            })
        return str(returned)

    def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method().estimateGas(tx_params.as_dict())

class GetCurrentBlockDifficultyMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getCurrentBlockDifficulty method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getCurrentBlockDifficulty")



    def block_call(self, debug:bool=False) -> int:
        _fn = self._underlying_method()
        returned = _fn.call({
                'from': self._operate
            })
        return int(returned)

    def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method().estimateGas(tx_params.as_dict())

class GetCurrentBlockGasLimitMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getCurrentBlockGasLimit method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getCurrentBlockGasLimit")



    def block_call(self, debug:bool=False) -> int:
        _fn = self._underlying_method()
        returned = _fn.call({
                'from': self._operate
            })
        return int(returned)

    def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method().estimateGas(tx_params.as_dict())

class GetCurrentBlockTimestampMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getCurrentBlockTimestamp method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getCurrentBlockTimestamp")



    def block_call(self, debug:bool=False) -> int:
        _fn = self._underlying_method()
        returned = _fn.call({
                'from': self._operate
            })
        return int(returned)

    def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method().estimateGas(tx_params.as_dict())

class GetEthBalanceMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getEthBalance method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address, validator)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getEthBalance")

    def validate_and_normalize_inputs(self, addr: str)->any:
        """Validate the inputs to the getEthBalance method."""
        self.validator.assert_valid(
            method_name='getEthBalance',
            parameter_name='addr',
            argument_value=addr,
        )
        addr = self.validate_and_checksum_address(addr)
        return (addr)



    def block_call(self,addr: str, debug:bool=False) -> int:
        _fn = self._underlying_method(addr)
        returned = _fn.call({
                'from': self._operate
            })
        return int(returned)

    def estimate_gas(self, addr: str, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        (addr) = self.validate_and_normalize_inputs(addr)
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method(addr).estimateGas(tx_params.as_dict())

class GetLastBlockHashMethod(ContractMethod): # pylint: disable=invalid-name
    """Various interfaces to the getLastBlockHash method."""

    def __init__(self, elib: MiliDoS, contract_address: str, contract_function: ContractFunction, validator: Validator=None):
        """Persist instance data."""
        super().__init__(elib, contract_address)
        self._underlying_method = contract_function
        self.sign = validator.getSignature("getLastBlockHash")



    def block_call(self, debug:bool=False) -> Union[bytes, str]:
        _fn = self._underlying_method()
        returned = _fn.call({
                'from': self._operate
            })
        return Union[bytes, str](returned)

    def estimate_gas(self, tx_params: Optional[TxParams] = None) -> int:
        """Estimate gas consumption of method call."""
        tx_params = super().normalize_tx_params(tx_params)
        return self._underlying_method().estimateGas(tx_params.as_dict())

class SignatureGenerator(Signatures):
    """
        The signature is generated for this and it is installed.
    """
    def __init__(self, abi: any):
        super().__init__(abi)

    def aggregate(self) -> str:
        return self._function_signatures["aggregate"]
    def get_block_hash(self) -> str:
        return self._function_signatures["getBlockHash"]
    def get_current_block_coinbase(self) -> str:
        return self._function_signatures["getCurrentBlockCoinbase"]
    def get_current_block_difficulty(self) -> str:
        return self._function_signatures["getCurrentBlockDifficulty"]
    def get_current_block_gas_limit(self) -> str:
        return self._function_signatures["getCurrentBlockGasLimit"]
    def get_current_block_timestamp(self) -> str:
        return self._function_signatures["getCurrentBlockTimestamp"]
    def get_eth_balance(self) -> str:
        return self._function_signatures["getEthBalance"]
    def get_last_block_hash(self) -> str:
        return self._function_signatures["getLastBlockHash"]

# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Multicall(ContractBase):
    """Wrapper class for Multicall Solidity contract."""
    _fn_aggregate: AggregateMethod
    """Constructor-initialized instance of
    :class:`AggregateMethod`.
    """

    _fn_get_block_hash: GetBlockHashMethod
    """Constructor-initialized instance of
    :class:`GetBlockHashMethod`.
    """

    _fn_get_current_block_coinbase: GetCurrentBlockCoinbaseMethod
    """Constructor-initialized instance of
    :class:`GetCurrentBlockCoinbaseMethod`.
    """

    _fn_get_current_block_difficulty: GetCurrentBlockDifficultyMethod
    """Constructor-initialized instance of
    :class:`GetCurrentBlockDifficultyMethod`.
    """

    _fn_get_current_block_gas_limit: GetCurrentBlockGasLimitMethod
    """Constructor-initialized instance of
    :class:`GetCurrentBlockGasLimitMethod`.
    """

    _fn_get_current_block_timestamp: GetCurrentBlockTimestampMethod
    """Constructor-initialized instance of
    :class:`GetCurrentBlockTimestampMethod`.
    """

    _fn_get_eth_balance: GetEthBalanceMethod
    """Constructor-initialized instance of
    :class:`GetEthBalanceMethod`.
    """

    _fn_get_last_block_hash: GetLastBlockHashMethod
    """Constructor-initialized instance of
    :class:`GetLastBlockHashMethod`.
    """

    SIGNATURES:SignatureGenerator = None

    def __init__(
        self,
        core_lib: MiliDoS,
        contract_address: str,
        validator: MulticallValidator = None,
    ):
        """Get an instance of wrapper for smart contract.
        """
        # pylint: disable=too-many-statements
        super().__init__()
        self.contract_address = contract_address
        web3 = core_lib.w3

        if not validator:
            validator = MulticallValidator(web3, contract_address)




        # if any middleware was imported, inject it
        try:
            MIDDLEWARE
        except NameError:
            pass
        else:
            try:
                for middleware in MIDDLEWARE:
                    web3.middleware_onion.inject(
                         middleware['function'], layer=middleware['layer'],
                    )
            except ValueError as value_error:
                if value_error.args == ("You can't add the same un-named instance twice",):
                    pass

        self._web3_eth = web3.eth
        functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=Multicall.abi()).functions
        signed = SignatureGenerator(Multicall.abi())
        validator.bindSignatures(signed)
        self.SIGNATURES = signed
        self._fn_aggregate = AggregateMethod(core_lib, contract_address, functions.aggregate, validator)
        self._fn_get_block_hash = GetBlockHashMethod(core_lib, contract_address, functions.getBlockHash, validator)
        self._fn_get_current_block_coinbase = GetCurrentBlockCoinbaseMethod(core_lib, contract_address, functions.getCurrentBlockCoinbase, validator)
        self._fn_get_current_block_difficulty = GetCurrentBlockDifficultyMethod(core_lib, contract_address, functions.getCurrentBlockDifficulty, validator)
        self._fn_get_current_block_gas_limit = GetCurrentBlockGasLimitMethod(core_lib, contract_address, functions.getCurrentBlockGasLimit, validator)
        self._fn_get_current_block_timestamp = GetCurrentBlockTimestampMethod(core_lib, contract_address, functions.getCurrentBlockTimestamp, validator)
        self._fn_get_eth_balance = GetEthBalanceMethod(core_lib, contract_address, functions.getEthBalance, validator)
        self._fn_get_last_block_hash = GetLastBlockHashMethod(core_lib, contract_address, functions.getLastBlockHash, validator)


    
    
    
    def aggregate(self, calls: List[MulticallCall]) -> Tuple[int, List[Union[bytes, str]]]:
        """
        Implementation of aggregate in contract Multicall
        Method of the function
    
    
    
        """
    
        return self._fn_aggregate.block_send(calls, self.call_contract_fee_amount,self.call_contract_fee_price,0,self.call_contract_debug_flag, self.call_contract_enforce_tx_receipt)
    
    
    
    
    
    
    
    def get_block_hash(self, block_number: int) -> Union[bytes, str]:
        """
        Implementation of get_block_hash in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_block_hash.block_call(block_number)
    
    
    
    def get_current_block_coinbase(self) -> str:
        """
        Implementation of get_current_block_coinbase in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_current_block_coinbase.block_call()
    
    
    
    def get_current_block_difficulty(self) -> int:
        """
        Implementation of get_current_block_difficulty in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_current_block_difficulty.block_call()
    
    
    
    def get_current_block_gas_limit(self) -> int:
        """
        Implementation of get_current_block_gas_limit in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_current_block_gas_limit.block_call()
    
    
    
    def get_current_block_timestamp(self) -> int:
        """
        Implementation of get_current_block_timestamp in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_current_block_timestamp.block_call()
    
    
    
    def get_eth_balance(self, addr: str) -> int:
        """
        Implementation of get_eth_balance in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_eth_balance.block_call(addr)
    
    
    
    def get_last_block_hash(self) -> Union[bytes, str]:
        """
        Implementation of get_last_block_hash in contract Multicall
        Method of the function
    
    
    
        """
    
    
    
    
    
        return self._fn_get_last_block_hash.block_call()

    def CallContractWait(self, t_long:int)-> "Multicall":
        self._fn_aggregate.setWait(t_long)
        self._fn_get_block_hash.setWait(t_long)
        self._fn_get_current_block_coinbase.setWait(t_long)
        self._fn_get_current_block_difficulty.setWait(t_long)
        self._fn_get_current_block_gas_limit.setWait(t_long)
        self._fn_get_current_block_timestamp.setWait(t_long)
        self._fn_get_eth_balance.setWait(t_long)
        self._fn_get_last_block_hash.setWait(t_long)
        return self


    @staticmethod
    def abi():
        """Return the ABI to the underlying contract."""
        return json.loads(
            '[{"constant":false,"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall.Call[]","name":"calls","type":"tuple[]"}],"name":"aggregate","outputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"bytes[]","name":"returnData","type":"bytes[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"}],"name":"getBlockHash","outputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCurrentBlockCoinbase","outputs":[{"internalType":"address","name":"coinbase","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCurrentBlockDifficulty","outputs":[{"internalType":"uint256","name":"difficulty","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCurrentBlockGasLimit","outputs":[{"internalType":"uint256","name":"gaslimit","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCurrentBlockTimestamp","outputs":[{"internalType":"uint256","name":"timestamp","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"getEthBalance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getLastBlockHash","outputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"}]'  # noqa: E501 (line-too-long)
        )

# pylint: disable=too-many-lines
