// Contract: CryptoMultisender
// Target function: function withdrawERC20Tokens(address _addressOfToken,  address _recipient, uint256 _value) public onlyOwner returns(bool success)
 false otherwise.
     * */
    function changeAffiliatePercentage(address _addressOfAffiliate, uint256 _percentage) public onlyOwner returns(bool success) { 
        require(isAffiliate[_addressOfAffiliate]);
        string storage affCode = affiliateCodeOfAddr[_addressOfAffiliate];
        commissionPercentage[affCode] = _percentage;
        return true;
    }

    /**
    * Allows the owner of this contract to remove an affiliate partner. 
    *
    * @param _addr The address of the affiliate partner.
    *
    * @return success True if affiliate partner is removed successfully. False otherwise. 
    **/
    function removeAffiliate(address _addr) public onlyOwner returns(bool success) {
        require(isAffiliate[_addr]);
        isAffiliate[_addr] = false;
        affiliateCodeToAddr[affiliateCodeOfAddr[_addr]] = address(0);
        emit AffiliatePartnershipRevoked(_addr, affiliateCodeOfAddr[_addr]);
        affiliateCodeOfAddr[_addr] = "No longer an affiliate partner";
        return true;
    }
    
    /**
     * Checks whether or not an ERC20 token has used its free trial of 100 drops. This is a constant 
     * function which does not alter the state of the contract and therefore does not require any gas 
     * or a signature to be executed. 
     * 
     * @param _addressOfToken The address of the token being queried.
     * 
     * @return hasFreeTrial true if the token being queried has not used its 100 first free trial drops, false
     * otherwise.
     * */
    function tokenHasFreeTrial(address _addressOfToken) public view returns(bool hasFreeTrial) {
        return tokenTrialDrops[_addressOfToken] < 100;
    }


    /**
     * Checks whether or not a user has a free trial. 
     * 
     * @param _addressOfUser The address of the user being queried.
     * 
     * @return hasFreeTrial true if the user address being queried has not used the first 100 free trial drops, false
     * otherwise.
     * */
    function userHasFreeTrial(address _addressOfUser) public view returns(bool hasFreeTrial) {
        return userTrialDrops[_addressOfUser] < 100;
    }
    
    /**
     * Checks how many remaining free trial drops a token has.
     * 
     * @param _addressOfToken the address of the token being queried.
     * 
     * @return remainingTrialDrops the total remaining free trial drops of a token.
     * */
    function getRemainingTokenTrialDrops(address _addressOfToken) public view returns(uint256 remainingTrialDrops) {
        if(tokenHasFreeTrial(_addressOfToken)) {
            uint256 maxTrialDrops =  100;
            return maxTrialDrops - tokenTrialDrops[_addressOfToken];
        } 
        return 0;
    }

    /**
     * Checks how many remaining free trial drops a user has.
     * 
     * @param _addressOfUser the address of the user being queried.
     * 
     * @return remainingTrialDrops the total remaining free trial drops of a user.
     * */
    function getRemainingUserTrialDrops(address _addressOfUser) public view returns(uint256 remainingTrialDrops) {
        if(userHasFreeTrial(_addressOfUser)) {
            uint256 maxTrialDrops =  100;
            return maxTrialDrops - userTrialDrops[_addressOfUser];
        }
        return 0;
    }
    
    /**
     * Allows for the price of drops to be changed by the owner of the contract. Any attempt made by 
     * any other account to invoke the function will result in a loss of gas and the price will remain 
     * untampered.
     * 
     * @return success true if function executes successfully, false otherwise.
     * */
    function setRate(uint256 _newRate) public onlyOwner returns(bool success) {
        require(
            _newRate != rate 
            && _newRate > 0
        );
        emit RateChanged(rate, _newRate);
        rate = _newRate;
        uint256 eth = 1 ether;
        dropUnitPrice = eth / rate;
        return true;
    }
    
    /**
     * Allows for the allowance of a token from its owner to this contract to be queried. 
     * 
     * As part of the ERC20 standard all tokens which fall under this category have an allowance 
     * function which enables owners of tokens to allow (or give permission) to another address 
     * to spend tokens on behalf of the owner. This contract uses this as part of its protocol.
     * Users must first give permission to the contract to transfer tokens on their behalf, however,
     * this does not mean that the tokens will ever be transferrable without the permission of the 
     * owner. This is a security feature which was implemented on this contract. It is not possible
     * for the owner of this contract or anyone else to transfer the tokens which belong to others. 
     * 
     * @param _addr The address of the token's owner.
     * @param _addressOfToken The contract address of the ERC20 token.
     * 
     * @return allowance The ERC20 token allowance from token owner to this contract. 
     * */
    function getTokenAllowance(address _addr, address _addressOfToken) public view returns(uint256 allowance) {
        ERC20Interface token = ERC20Interface(_addressOfToken);
        return token.allowance(_addr, address(this));
    }
    
    fallback() external payable {
        revert();
    }

    receive() external payable {
        revert();
    }
    
    /**
    * Checks if two strings are the same.
    *
    * @param _a String 1
    * @param _b String 2
    *
    * @return areEqual True if both strings are the same. False otherwise. 
    **/
    function stringsAreEqual(string memory _a, string memory _b) internal pure returns(bool areEqual) {
        bytes32 hashA = keccak256(abi.encodePacked(_a));
        bytes32 hashB = keccak256(abi.encodePacked(_b));
        return hashA == hashB;
    }
    
    /**
     * Allows for the distribution of Ether to be transferred to multiple recipients at 
     * a time. 
     * 
     * @param _recipients The list of addresses which will receive tokens. 
     * @param _values The corresponding amounts that the recipients will receive 
     * @param _afCode If the user is affiliated with a partner, they will provide this code so that 
     * the parter is paid commission.
     * 
     * @return success true if function executes successfully, false otherwise.
     * */
    function airdropNativeCurrency(address[] memory _recipients, uint256[] memory _values, uint256 _totalToSend, string memory _afCode) public payable returns(bool success) {
        require(_recipients.length == _values.length, "Total number of recipients and values are not equal");
        uint256 totalEthValue = _totalToSend;
        uint256 price = _recipients.length * dropUnitPrice;
        uint256 totalCost = totalEthValue + price;
        bool userHasTrial = userHasFreeTrial(msg.sender);
        bool isVIP = checkIsPremiumMember(msg.sender) == true;
        require(
            msg.value >= totalCost || isVIP || userHasTrial, 
            "Not enough funds sent with transaction!"
        );
        _afCode = processAffiliateCode(_afCode);
        if(!isVIP && !userHasTrial) {
            distributeCommission(price, _afCode);
        }
        if((isVIP || userHasTrial) && msg.value > _totalToSend) {
            payable(msg.sender).transfer((msg.value) - _totalToSend);
        } else {
            giveChange(totalCost);
        }
        for(uint i = 0; i < _recipients.length; i++) {
            payable(_recipients[i]).transfer(_values[i]);
        }
        if(userHasTrial) {
            userTrialDrops[msg.sender] = userTrialDrops[msg.sender] + _recipients.length;
        }
        emit EthAirdrop(msg.sender, _recipients.length, totalEthValue);
        return true;
    }

    /**
     * Allows for the distribution of an ERC20 token to be transferred to multiple recipients at 
     * a time. This function facilitates batch transfers of differing values (i.e., all recipients
     * can receive different amounts of tokens).
     * 
     * @param _addressOfToken The contract address of an ERC20 token.
     * @param _recipients The list of addresses which will receive tokens. 
     * @param _values The corresponding values of tokens which each address will receive.
     * @param _optimized Should only be enabled for tokens with gas optimized distribution functions. 
     * @param _afCode If the user is affiliated with a partner, they will provide this code so that 
     * the parter is paid commission.
     * 
     * @return success true if function executes successfully, false otherwise.
     * */    
    function erc20Airdrop(address _addressOfToken,  address[] memory _recipients, uint256[] memory _values, uint256 _totalToSend, bool _isDeflationary, bool _optimized, string memory _afCode) public payable returns(bool success) {
        string memory afCode = processAffiliateCode(_afCode);
        ERC20Interface token = ERC20Interface(_addressOfToken);
        require(_recipients.length == _values.length, "Total number of recipients and values are not equal");
        uint256 price = _recipients.length * dropUnitPrice;
        bool isPremiumOrListed = checkIsPremiumMember(msg.sender) || checkIsListedToken(_addressOfToken);
        bool eligibleForFreeTrial = tokenHasFreeTrial(_addressOfToken) && userHasFreeTrial(msg.sender);
        require(
            msg.value >= price || tokenHasFreeTrial(_addressOfToken) || userHasFreeTrial(msg.sender) || isPremiumOrListed,
            "Not enough funds sent with transaction!"
        );
        if((eligibleForFreeTrial || isPremiumOrListed) && msg.value > 0) {
            payable(msg.sender).transfer(msg.value);
        } else {
            giveChange(price);
        }

        if(_optimized) {
            token.transferFrom(msg.sender, address(this), _totalToSend);
            token.gasOptimizedAirdrop(_recipients,_values);
        } else {
            if(!_isDeflationary) {
                token.transferFrom(msg.sender, address(this), _totalToSend);
                for(uint i = 0; i < _recipients.length; i++) {
                    token.transfer(_recipients[i], _values[i]);
                }
                if(token.balanceOf(address(this)) > 0) {
                    token.transfer(msg.sender,token.balanceOf(address(this)));
                }
            } else {
                for(uint i=0; i < _recipients.length; i++) {
                    token.transferFrom(msg.sender, _recipients[i], _values[i]);
                }
            }
        }

        if(tokenHasFreeTrial(_addressOfToken)) {
            tokenTrialDrops[_addressOfToken] = tokenTrialDrops[_addressOfToken] + _recipients.length;
        }
        if(userHasFreeTrial(msg.sender)) {
            userTrialDrops[msg.sender] = userTrialDrops[msg.sender] + _recipients.length;
        }
        if(!eligibleForFreeTrial && !isPremiumOrListed) {
            distributeCommission(_recipients.length * dropUnitPrice, afCode);
        }
        emit TokenAirdrop(msg.sender, _addressOfToken, _recipients.length);
        return true;
    }


    /**
     * Allows for the distribution of ERC721 tokens to be transferred to multiple recipients at 
     * a time. 
     * 
     * @param _addressOfNFT The contract address of an ERC721 token collection.
     * @param _recipients The list of addresses which will receive tokens. 
     * @param _tokenIds The corresponding IDs of the NFT collection which each address will receive.
     * @param _optimized Should only be enabled for ERC721 token collections with gas optimized distribution functions. 
     * @param _afCode If the user is affiliated with a partner, they will provide this code so that 
     * the parter is paid commission.
     * 
     * @return success true if function executes successfully, false otherwise.
     * */ 
    function erc721Airdrop(address _addressOfNFT, address[] memory _recipients, uint256[] memory _tokenIds, bool _optimized, string memory _afCode) public payable returns(bool success) {
        require(_recipients.length == _tokenIds.length, "Total number of recipients and total number of NFT IDs are not the same");
        string memory afCode = processAffiliateCode(_afCode);
        ERC721Interface erc721 = ERC721Interface(_addressOfNFT);
        uint256 price = _recipients.length * dropUnitPrice;
        bool isPremiumOrListed = checkIsPremiumMember(msg.sender) || checkIsListedToken(_addressOfNFT);
        bool eligibleForFreeTrial = tokenHasFreeTrial(_addressOfNFT) && userHasFreeTrial(msg.sender);
        require(
            msg.value >= price || eligibleForFreeTrial || isPremiumOrListed,
            "Not enough funds sent with transaction!"
        );
        if((eligibleForFreeTrial || isPremiumOrListed) && msg.value > 0) {
            payable(msg.sender).transfer(msg.value);
        } else {
            giveChange(price);
        }
        if(_optimized){
            erc721.gasOptimizedAirdrop(msg.sender,_recipients,_tokenIds);
        } else {
            for(uint i = 0; i < _recipients.length; i++) {
                erc721.transferFrom(msg.sender, _recipients[i], _tokenIds[i]);
            }
        }
        if(tokenHasFreeTrial(_addressOfNFT)) {
            tokenTrialDrops[_addressOfNFT] = tokenTrialDrops[_addressOfNFT] + _recipients.length;
        }
        if(userHasFreeTrial(msg.sender)) {
            userTrialDrops[msg.sender] = userTrialDrops[msg.sender] + _recipients.length;
        }
        if(!eligibleForFreeTrial && !isPremiumOrListed) {
            distributeCommission(_recipients.length * dropUnitPrice, afCode);
        }
        emit NftAirdrop(msg.sender, _addressOfNFT, _recipients.length);
        return true;
    }

    /**
     * Allows for the distribution of ERC1155 tokens to be transferred to multiple recipients at 
     * a time. 
     * 
     * @param _addressOfNFT The contract address of an ERC1155 token contract.
     * @param _recipients The list of addresses which will receive tokens. 
     * @param _ids The corresponding IDs of the token collection which each address will receive.
     * @param _amounts The amount of tokens to send from each token type.
     * @param _optimized Should only be enabled for ERC721 token collections with gas optimized distribution functions. 
     * @param _afCode If the user is affiliated with a partner, they will provide this code so that 
     * the parter is paid commission.
     * 
     * @return success true if function executes successfully, false otherwise.
     * */ 
    function erc1155Airdrop(address _addressOfNFT, address[] memory _recipients, uint256[] memory _ids, uint256[] memory _amounts, bool _optimized, string memory _afCode) public payable returns(bool success) {
        require(_recipients.length == _ids.length, "Total number of recipients and total number of NFT IDs are not the same");
        require(_recipients.length == _amounts.length, "Total number of recipients and total number of amounts are not the same");
        string memory afCode = processAffiliateCode(_afCode);
        ERC1155Interface erc1155 = ERC1155Interface(_addressOfNFT);
        uint256 price = _recipients.length * dropUnitPrice;
        bool isPremiumOrListed = checkIsPremiumMember(msg.sender) || checkIsListedToken(_addressOfNFT);
        bool eligibleForFreeTrial = tokenHasFreeTrial(_addressOfNFT) && userHasFreeTrial(msg.sender);
        require(
            msg.value >= price || eligibleForFreeTrial || isPremiumOrListed,
            "Not enough funds sent with transaction!"
        );
        if((eligibleForFreeTrial || isPremiumOrListed) && msg.value > 0) {
            payable(msg.sender).transfer(msg.value);
        } else {
            giveChange(price);
        }
        if(_optimized){
            erc1155.gasOptimizedAirdrop(msg.sender,_recipients,_ids,_amounts);
        } else {
            for(uint i = 0; i < _recipients.length; i++) {
                erc1155.safeTransferFrom(msg.sender, _recipients[i], _ids[i], _amounts[i], "");
            }
        }
        if(tokenHasFreeTrial(_addressOfNFT)) {
            tokenTrialDrops[_addressOfNFT] = tokenTrialDrops[_addressOfNFT] + _recipients.length;
        }
        if(userHasFreeTrial(msg.sender)) {
            userTrialDrops[msg.sender] = userTrialDrops[msg.sender] + _recipients.length;
        }
        if(!eligibleForFreeTrial && !isPremiumOrListed) {
            distributeCommission(_recipients.length * dropUnitPrice, afCode);
        }
        emit NftAirdrop(msg.sender, _addressOfNFT, _recipients.length);
        return true;
    }


    /**
    * Send the owner and affiliates commissions.
    **/
    function distributeCommission(uint256 _profits, string memory _afCode) internal {
        if(!stringsAreEqual(_afCode,"void") && isAffiliate[affiliateCodeToAddr[_afCode]]) {
            uint256 commission = _profits * commissionPercentage[_afCode] / 100;
            payable(owner).transfer(_profits - commission);
            payable(affiliateCodeToAddr[_afCode]).transfer(commission);
            emit CommissionPaid(affiliateCodeToAddr[_afCode], commission);
        } else {
            payable(owner).transfer(_profits);
        }
    }


    /**
     * Allows the owner of the contract to withdraw any funds that may reside on the contract address.
     * */
    function withdrawFunds() public onlyOwner returns(bool success) {
        payable(owner).transfer(address(this).balance);
        return true;
    }