contract WardenRouterV2 is Ownable {
    using TransferHelper for IERC20;
    
    IWardenPreTrade2 public preTrade;

    IWETH public immutable weth;
    IERC20 private constant ETHER_ERC20 = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
    
    event UpdatedWardenPreTrade(
        IWardenPreTrade2 indexed preTrade
    );

    /**
    * @dev When fee is collected by WardenSwap for a trade, this event will be emitted
    * @param token Collected token
    * @param wallet Collector address
    * @param amount Amount of fee collected
    */
    event ProtocolFee(
        IERC20  indexed   token,
        address indexed   wallet,
        uint256           amount
    );

    /**
    * @dev When fee is collected by WardenSwap's partners for a trade, this event will be emitted
    * @param partnerId Partner ID
    * @param token Collected token
    * @param wallet Collector address
    * @param amount Amount of fee collected
    */
    event PartnerFee(
        uint256 indexed   partnerId,
        IERC20  indexed   token,
        address indexed   wallet,
        uint256           amount
    );

    /**
    * @dev When the new trade occurs (and success), this event will be emitted.
    * @param srcAsset Source token
    * @param srcAmount Amount of source token
    * @param destAsset Destination token
    * @param destAmount Amount of destination token
    * @param trader User address
    */
    event Trade(
        address indexed srcAsset,
        uint256         srcAmount,
        address indexed destAsset,
        uint256         destAmount,
        address indexed trader,
        address         receiver,
        bool            hasSplitted
    );

    constructor(
        IWardenPreTrade2 _preTrade,
        IWETH _weth
    ) {
        preTrade = _preTrade;
        weth = _weth;
        
        emit UpdatedWardenPreTrade(_preTrade);
    }

    function updateWardenPreTrade(
        IWardenPreTrade2 _preTrade
    )
        external
        onlyOwner
    {
        preTrade = _preTrade;
        emit UpdatedWardenPreTrade(_preTrade);
    }

    /**
    * @dev Performs a trade with single volume
    * @param _swap Warden Swap contract
    * @param _data Warden Swap payload
    * @param _deposits Source token receiver
    * @param _src Source token
    * @param _srcAmount Amount of source tokens
    * @param _dest Destination token
    * @param _minDestAmount Minimum of destination token amount
    * @param _receiver Destination token receiver
    * @param _partnerId Partner id for fee sharing / Referral
    * @param _metaData Reserved for upcoming features
    * @return _destAmount Amount of actual destination tokens
    */
    function swap(
        IWardenSwap2    _swap,
        bytes calldata  _data,
        address     _deposits,
        IERC20      _src,
        uint256     _srcAmount,
        IERC20      _dest,
        uint256     _minDestAmount,
        address     _receiver,
        uint256     _partnerId,
        uint256     _metaData
    )
        external
        payable
        returns(uint256 _destAmount)
    {
        if (_receiver == address(0)) {
            _receiver = msg.sender;
        }

        // Collect fee
        uint256 newSrcAmount = _preTradeAndCollectFee(
            _src,
            _dest,
            _srcAmount,
            msg.sender,
            _receiver,
            _partnerId,
            _metaData
        );

        // Wrap ETH
        if (ETHER_ERC20 == _src) {
            require(msg.value == _srcAmount, "WardenRouter::swap: Ether source amount mismatched");
            weth.deposit{value: newSrcAmount}();
            
            // Transfer user tokens to target
            IERC20(address(weth)).safeTransfer(_deposits, newSrcAmount);
        } else {
            // Transfer user tokens to target
            _src.safeTransferFrom(msg.sender, _deposits, newSrcAmount);
        }

        bytes memory payload = abi.encodeWithSelector(IWardenSwap2.trade.selector,
            _data,
            _src,
            newSrcAmount,
            _srcAmount,
            _dest,
            _receiver,
            msg.sender,
            _partnerId,
            _metaData
        );

        _destAmount = _internalSwap(
            _swap,
            payload,
            _dest,
            _minDestAmount,
            _receiver
        );
        emit Trade(address(_src), _srcAmount, address(_dest), _destAmount, msg.sender, _receiver, false);
    }

    /**
    * @dev Performs a trade by splitting volumes
    * @param _swap Warden Swap contract
    * @param _data Warden Swap payload
    * @param _deposits Source token receivers
    * @param _volumes Volume percentages
    * @param _src Source token
    * @param _totalSrcAmount Amount of source tokens
    * @param _dest Destination token
    * @param _minDestAmount Minimum of destination token amount
    * @param _receiver Destination token receiver
    * @param _partnerId Partner id for fee sharing / Referral
    * @param _metaData Reserved for upcoming features
    * @return _destAmount Amount of actual destination tokens
    */
    function swapSplit(
        IWardenSwap2    _swap,
        bytes calldata  _data,
        address[] memory _deposits,
        uint256[] memory _volumes,
        IERC20      _src,
        uint256     _totalSrcAmount,
        IERC20      _dest,
        uint256     _minDestAmount,
        address     _receiver,
        uint256     _partnerId,
        uint256     _metaData
    )
        external
        payable
        returns(uint256 _destAmount)
    {
        if (_receiver == address(0)) {
            _receiver = msg.sender;
        }

        // Collect fee
        uint256 newTotalSrcAmount = _preTradeAndCollectFee(
            _src,
            _dest,
            _totalSrcAmount,
            msg.sender,
            _receiver,
            _partnerId,
            _metaData
        );

        // Wrap ETH
        if (ETHER_ERC20 == _src) {
            require(msg.value == _totalSrcAmount, "WardenRouter::swapSplit: Ether source amount mismatched");
            weth.deposit{value: newTotalSrcAmount}();
        }

        // Transfer user tokens to targets
        _depositVolumes(
            newTotalSrcAmount,
            _deposits,
            _volumes,
            _src
        );
        

        bytes memory payload = abi.encodeWithSelector(IWardenSwap2.tradeSplit.selector,
            _data,
            _volumes,
            _src,
            newTotalSrcAmount,
            _totalSrcAmount,
            _dest,
            _receiver,
            msg.sender,
            _partnerId,
            _metaData
        );

        _destAmount = _internalSwap(
            _swap,
            payload,
            _dest,
            _minDestAmount,
            _receiver
        );
        emit Trade(address(_src), _totalSrcAmount, address(_dest), _destAmount, msg.sender, _receiver, true);
    }

    function _depositVolumes(
        uint256 newTotalSrcAmount,
        address[] memory _deposits,
        uint256[] memory _volumes,
        IERC20           _src
    )
        private
    {
        {
            uint256 amountRemain = newTotalSrcAmount;
            for (uint i = 0; i < _deposits.length; i++) {
                uint256 amountForThisRound;
                if (i == _deposits.length - 1) {
                    amountForThisRound = amountRemain;
                } else {
                    amountForThisRound = newTotalSrcAmount * _volumes[i] / 100;
                    amountRemain = amountRemain - amountForThisRound;
                }
            
                if (ETHER_ERC20 == _src) {
                    IERC20(address(weth)).safeTransfer(_deposits[i], amountForThisRound);
                } else {
                    _src.safeTransferFrom(msg.sender, _deposits[i], amountForThisRound);
                }
            }
        }
    }

    function _internalSwap(
        IWardenSwap2 _swap,
        bytes memory _payload,
        IERC20       _dest,
        uint256      _minDestAmount,
        address      _receiver
    )
        private
        returns (uint256 _destAmount)
    {
        // Record dest asset for later consistency check.
        uint256 destAmountBefore = ETHER_ERC20 == _dest ? _receiver.balance : _dest.balanceOf(_receiver);

        {
            // solhint-disable-next-line avoid-low-level-calls
            (bool success, bytes memory result) = address(_swap).call(_payload);
            if (!success) {
                // Next 5 lines from https://ethereum.stackexchange.com/a/83577
                if (result.length < 68) revert();
                assembly {
                    result := add(result, 0x04)
                }
                revert(abi.decode(result, (string)));
            }
        }

        _destAmount = ETHER_ERC20 == _dest ? _receiver.balance - destAmountBefore : _dest.balanceOf(_receiver) - destAmountBefore;

        // Throw exception if destination amount doesn't meet user requirement.
        require(_destAmount >= _minDestAmount, "WardenRouter::_internalSwap: destination amount is too low.");
    }

    function _preTradeAndCollectFee(
        IERC20      _src,
        IERC20      _dest,
        uint256     _srcAmount,
        address     _trader,
        address     _receiver,
        uint256     _partnerId,
        uint256     _metaData
    )
        private
        returns (uint256 _newSrcAmount)
    {
        // Collect fee
        (uint256[] memory fees, address[] memory feeWallets) = preTrade.preTradeAndFee(
            _src,
            _dest,
            _srcAmount,
            _trader,
            _receiver,
            _partnerId,
            _metaData
        );
        _newSrcAmount = _srcAmount;
        if (fees.length > 0) {
            if (fees[0] > 0) {
                _collectFee(
                    _trader,
                    _src,
                    fees[0],
                    feeWallets[0]
                );
                _newSrcAmount -= fees[0];
            }
            if (fees.length == 2 && fees[1] > 0) {
                _partnerFee(
                    _trader,
                    _partnerId, // partner id
                    _src,
                    fees[1],
                    feeWallets[1]
                );
                _newSrcAmount -= fees[1];
            }
        }
    }
    
    function _collectFee(
        address _trader,
        IERC20  _token,
        uint256 _fee,
        address _feeWallet
    )
        private
    {
        if (ETHER_ERC20 == _token) {
            (bool success, ) = payable(_feeWallet).call{value: _fee}(""); // Send ether to fee collector
            require(success, "WardenRouter::_collectFee: Transfer fee of ether failed.");
        } else {
            _token.safeTransferFrom(_trader, _feeWallet, _fee); // Send token to fee collector
        }
        emit ProtocolFee(_token, _feeWallet, _fee);
    }

    function _partnerFee(
        address _trader,
        uint256 _partnerId,
        IERC20  _token,
        uint256 _fee,
        address _feeWallet
    )
        private
    {
        if (ETHER_ERC20 == _token) {
            (bool success, ) = payable(_feeWallet).call{value: _fee}(""); // Send back ether to partner
            require(success, "WardenRouter::_partnerFee: Transfer fee of ether failed.");
        } else {
            _token.safeTransferFrom(_trader, _feeWallet, _fee);
        }
        emit PartnerFee(_partnerId, _token, _feeWallet, _fee);
    }

    /**
    * @dev Performs a trade ETH -> WETH
    * @param _receiver Receiver address
    * @return _destAmount Amount of actual destination tokens
    */
    function tradeEthToWeth(
        address     _receiver
    )
        external
        payable
        returns(uint256 _destAmount)
    {
        if (_receiver == address(0)) {
            _receiver = msg.sender;
        }

        weth.deposit{value: msg.value}();
        IERC20(address(weth)).safeTransfer(_receiver, msg.value);
        _destAmount = msg.value;
        emit Trade(address(ETHER_ERC20), msg.value, address(weth), _destAmount, msg.sender, _receiver, false);
    }
    
    /**
    * @dev Performs a trade WETH -> ETH
    * @param _srcAmount Amount of source tokens
    * @param _receiver Receiver address
    * @return _destAmount Amount of actual destination tokens
    */
    function tradeWethToEth(
        uint256     _srcAmount,
        address     _receiver
    )
        external
        returns(uint256 _destAmount)
    {
        if (_receiver == address(0)) {
            _receiver = msg.sender;
        }

        IERC20(address(weth)).safeTransferFrom(msg.sender, address(this), _srcAmount);
        weth.withdraw(_srcAmount);
        (bool success, ) = _receiver.call{value: _srcAmount}(""); // Send back ether to receiver
        require(success, "WardenRouter::tradeWethToEth: Transfer ether back to receiver failed.");
        _destAmount = _srcAmount;
        emit Trade(address(weth), _srcAmount, address(ETHER_ERC20), _destAmount, msg.sender, _receiver, false);
    }

    // Receive ETH in case of trade WETH -> ETH
    receive() external payable {
        require(msg.sender == address(weth), "WardenRouter: Receive Ether only from WETH");
    }

    // In case of an expected and unexpected event that has some token amounts remain in this contract, owner can call to collect them.
    function collectRemainingToken(
        IERC20  _token,
        uint256 _amount
    )
      external
      onlyOwner
    {
        _token.safeTransfer(msg.sender, _amount);
    }

    // In case of an expected and unexpected event that has some ether amounts remain in this contract, owner can call to collect them.
    function collectRemainingEther(
        uint256 _amount
    )
      external
      onlyOwner
    {
        (bool success, ) = msg.sender.call{value: _amount}(""); // Send back ether to sender
        require(success, "WardenRouter::collectRemainingEther: Transfer ether back to caller failed.");
    }
}
// Receive ETH in case of trade WETH -> ETH