// Contract: CryptoMultisender
// Target function: function tokenHasFreeTrial(address _addressOfToken) public view returns(bool hasFreeTrial)
n(address token, address sentTo, uint256 value);
    event CommissionPaid(address indexed to, uint256 value);
    event NewPremiumMembership(address indexed premiumMember);
    event NewAffiliatePartnership(address indexed newAffiliate, string indexed affiliateCode);
    event AffiliatePartnershipRevoked(address indexed affiliate, string indexed affiliateCode);
    
    constructor() {
        rate = 3000;
        dropUnitPrice = 333333333333333; 
        oneDayMembershipFee = 9e17;
        sevenDayMembershipFee = 125e16;
        oneMonthMembershipFee = 2e18;
        lifetimeMembershipFee = 25e17;
        tokenListingFee = 5e18;
        deprecatedMultisenderAddress=address(0xF521007C7845590C6c5ae46833DEFa0A68883CD4);
    }

    /**
     * Allows the owner of this contract to change the fees for users to become premium members.
     * 
     * @param _oneDayFee Fee for single day membership.
     * @param _sevenDayFee Fee for one week membership.
     * @param _oneMonthFee Fee for one month membership.
     * @param _lifetimeFee Fee for lifetime membership.
     * 
     * @return success True if the fee is changed successfully. False otherwise.
     * */
    function setMembershipFees(uint256 _oneDayFee, uint256 _sevenDayFee, uint256 _oneMonthFee, uint256 _lifetimeFee) public onlyOwner returns(bool success) {
        require(_oneDayFee>0 && _oneDayFee<_sevenDayFee && _sevenDayFee<_oneMonthFee && _oneMonthFee<_lifetimeFee);
        oneDayMembershipFee = _oneDayFee;
        sevenDayMembershipFee = _sevenDayFee;
        oneMonthMembershipFee = _oneMonthFee;
        lifetimeMembershipFee = _lifetimeFee;
        return true;
    }

    /**
     * Allows for the conversion of an unsigned integer to a string value. 
     * 
     * @param _i The value of the unsigned integer
     * 
     * @return _uintAsString The string value of the unsigned integer.
     * */
    function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
        if (_i == 0) {
            return "0";
        }
        uint j = _i;
        uint len;
        while (j != 0) {
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len;
        while (_i != 0) {
            k = k-1;
            uint8 temp = (48 + uint8(_i - _i / 10 * 10));
            bytes1 b1 = bytes1(temp);
            bstr[k] = b1;
            _i /= 10;
        }
        return string(bstr);
    }

    /**
    * Used to give change to users who accidentally send too much ETH to payable functions. 
    *
    * @param _price The service fee the user has to pay for function execution. 
    **/
    function giveChange(uint256 _price) internal {
        if(msg.value > _price) {
            uint256 change = msg.value - _price;
            payable(msg.sender).transfer(change);
        }
    }
    
    /**
    * Ensures that the correct affiliate code is used and also ensures that affiliate partners
    * are not able to 'jack' commissions from existing users who they are not affiliated with. 
    *
    * @param _afCode The affiliate code provided by the user.
    *
    * @return code The correct affiliate code or void.
    **/
    function processAffiliateCode(string memory _afCode) internal returns(string memory code) {
        if(stringsAreEqual(isAffiliatedWith[msg.sender], "void") || !isAffiliate[affiliateCodeToAddr[_afCode]]) {
            isAffiliatedWith[msg.sender] = "void";
            return "void";
        }
        if(!stringsAreEqual(_afCode, "") && stringsAreEqual(isAffiliatedWith[msg.sender],"") 
                                                                && affiliateCodeExists[_afCode]) {
            if(affiliateCodeToAddr[_afCode] == msg.sender) {
                return "void";
            }
            isAffiliatedWith[msg.sender] = _afCode;
        }
        if(stringsAreEqual(_afCode,"") && !stringsAreEqual(isAffiliatedWith[msg.sender],"")) {
            _afCode = isAffiliatedWith[msg.sender];
        } 
        if(stringsAreEqual(_afCode,"") || !affiliateCodeExists[_afCode]) {
            isAffiliatedWith[msg.sender] = "void";
            _afCode = "void";
        }
        return _afCode;
    }

    /**
     * Allows users to check if a user is a premium member or not. 
     * 
     * @param _addr The address of the user. 
     * 
     * @return isMember True if the user is a premium member, false otherwise.
     * */
    function checkIsPremiumMember(address _addr) public view returns(bool isMember) {
        return membershipExpiryTime[_addr] >= block.timestamp || isGrantedPremiumMember[_addr];
    }

    /**
    * Allows the owner of this contract to grant users with premium membership.
    *
    * @param _addr The address of the user who is being granted premium membership.
    *
    * @return success True if premium membership is granted successfully. False otherwise. 
    **/
    function grantPremiumMembership(address _addr) public onlyOwner returns(bool success) {
        require(checkIsPremiumMember(_addr) != true, "Is already premiumMember member");
        isGrantedPremiumMember[_addr] = true;
        emit NewPremiumMembership(_addr);
        return true; 
    }

    /**
    * Allows the owner of this contract to revoke a granted membership.
    *
    * @param _addr The address of the user whos membership is being revoked.
    *
    * @return success True if membership is revoked successfully. False otherwise. 
    **/
    function revokeGrantedPremiumMembership(address _addr) public onlyOwner returns(bool success) {
        require(isGrantedPremiumMember[_addr], "Not a granted membership");
        isGrantedPremiumMember[_addr] = false;
        return true;
    }

    /**
     * Allows the owner of the contract to grant a premium membership discount for a specified user.
     * 
     * @param _addr The address of the user.
     * @param _discount The discount being granted.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function setPremiumMembershipDiscount(address _addr, uint256 _discount) public onlyOwner returns(bool success) {
        premiumMembershipDiscount[_addr] = _discount;
        return true;
    }

    /**
     * Allows users to check VIP membership fees for a specific address. This is useful for validating if a discount
     * has been granted for the specified user. 
     * 
     * @param _addr The address of the user.
     * @param _fee The default fee. 
     * 
     * @return fee The membership fee for the specified user. 
     * 
     * */
    function getPremiumMembershipFeeOfUser(address _addr, uint256 _fee) public view returns(uint256 fee) {
        if(premiumMembershipDiscount[_addr] > 0) {
            return _fee * premiumMembershipDiscount[_addr] / 100;
        }
        return _fee;
    }



    /**
     * Allows the owner of the contract to set the contract address of the old multisender SC.
     * 
     * @param _addr The updated address.
     * */
    function setDeprecatedMultisenderAddress(address _addr) public onlyOwner {
        deprecatedMultisenderAddress = _addr;
    }


    /**
     * This function checks if a user address has a membership on the old SC.
     * 
     * @param _who The address of the user.
     * 
     * @return True if the user is a member on the old SC, false otherwise.
     * */
    function isMemberOfOldMultisender(address _who) public view returns(bool) {
        DeprecatedMultisenderSC oldMultisender = DeprecatedMultisenderSC(deprecatedMultisenderAddress);
        return oldMultisender.isPremiumMember(_who);
    }


    /**
     * Allows users to transfer their membership from the old SC to this SC. 
     * 
     * @return True if there is a membership to be transferred, false otherwise. 
     * */
    function transferMembership() public returns(bool) {
        require(isMemberOfOldMultisender(msg.sender), "No membership to transfer");
        membershipExpiryTime[msg.sender] = block.timestamp + (36500 * 1 days);
        return true;
    }
    

    /**
     * This function is invoked internally the functions for purchasing memberships.
     * 
     * @param _days The number of days that the membership will be valid for. 
     * @param _fee The fee that is to be paid. 
     * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
     * an affiliate code so the partner gets commission.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function assignMembership(uint256 _days, uint256 _fee, string memory _afCode) internal returns(bool success) {
        require(checkIsPremiumMember(msg.sender) != true, "Is already premiumMember member");
        uint256 fee = getPremiumMembershipFeeOfUser(msg.sender, _fee);
        require(
            msg.value >= fee,
            string(abi.encodePacked(
                "premiumMember fee is: ", uint2str(fee), ". Not enough funds sent. ", uint2str(msg.value)
            ))
        );
        membershipExpiryTime[msg.sender] = block.timestamp + (_days * 1 days);
        _afCode = processAffiliateCode(_afCode);
        giveChange(fee);
        distributeCommission(fee, _afCode);
        emit NewPremiumMembership(msg.sender);
        return true; 
    }

    /**
    * Allows users to become lifetime members.
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeLifetimeMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(36500, lifetimeMembershipFee, _afCode);
        return true;
    }


    /**
    * Allows users to become members for 1 day.
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeOneDayMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(1, oneDayMembershipFee, _afCode);
        return true;
    }


    /**
    * Allows users to become members for 7 days.
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeOneWeekMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(7, sevenDayMembershipFee, _afCode);
        return true;
    }


    /**
    * Allows users to become members for 1 month
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeOneMonthMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(31, oneMonthMembershipFee, _afCode);
        return true;
    }


    /**
     * Allows users to check whether or not a token is listed.
     * 
     * @param _tokenAddr The address of the token to query.
     * 
     * @return isListed True if the token is listed, false otherwise. 
     * */
    function checkIsListedToken(address _tokenAddr) public view returns(bool isListed) {
        return isListedToken[_tokenAddr] || isGrantedListedToken[_tokenAddr];
    }


    /**
     * Allows the owner of the contract to set a listing discount for a specified token.
     * 
     * @param _tokenAddr The address of the token that will receive the discount. 
     * @param _discount The discount that will be applied. 
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function setTokenListingFeeDiscount(address _tokenAddr, uint256 _discount) public onlyOwner returns(bool success) {
        tokenListingFeeDiscount[_tokenAddr] = _discount;
        return true;
    }

    /**
     * Allows users to query the listing fee for a token. This is useful to verify that a discount has been set. 
     * 
     * @param _tokenAddr The address of the token. 
     * 
     * @return fee The listing fee for the token. 
     * */
    function getListingFeeForToken(address _tokenAddr) public view returns(uint256 fee) {
        if(tokenListingFeeDiscount[_tokenAddr] > 0) {
            return tokenListingFee * tokenListingFeeDiscount[_tokenAddr] / 100;
        }
        return tokenListingFee;
    }

    /**
     * Allows users to list a token of their choosing. 
     * 
     * @param _tokenAddr The address of the token that will be listed. 
     * @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 purchaseTokenListing(address _tokenAddr, string memory _afCode) public payable returns(bool success) {
        require(!checkIsListedToken(_tokenAddr), "Token is already listed");
        _afCode = processAffiliateCode(_afCode);
        uint256 fee = getListingFeeForToken(_tokenAddr);
        require(msg.value >= fee, "Not enough funds sent for listing");
        isListedToken[_tokenAddr] = true;
        giveChange(fee);
        distributeCommission(fee, _afCode);
        return true;
    }

    /**
     * Allows the owner of the contract to revoke a granted token listing. 
     * 
     * @param _tokenAddr The address of the token that is being delisted. 
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function revokeGrantedTokenListing(address _tokenAddr) public onlyOwner returns(bool success) {
        require(checkIsListedToken(_tokenAddr), "Is not listed token");
        isGrantedListedToken[_tokenAddr] = false;
        return  true;
    }


    /**
     * Allows the owner of the contract to grant a token a free listing. 
     * 
     * @param _tokenAddr The address of the token being listed.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function grantTokenListing(address _tokenAddr) public onlyOwner returns(bool success){
        require(!checkIsListedToken(_tokenAddr), "Token is already listed");
        isGrantedListedToken[_tokenAddr] = true;
        return true;
    }

    /**
     * Allows the owner of the contract to modify the token listing fee. 
     * 
     * @param _newFee The new fee for token listings. 
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function setTokenListingFee(uint256 _newFee) public onlyOwner returns(bool success){
        tokenListingFee = _newFee;
        return true;
    }
    
    /**
    * Allows the owner of this contract to add an affiliate partner.
    *
    * @param _addr The address of the new affiliate partner.
    * @param _code The affiliate code.
    * 
    * @return success True if the affiliate has been added successfully. False otherwise. 
    **/
    function addAffiliate(address _addr, string memory _code, uint256 _percentage) public onlyOwner returns(bool success) {
        require(!isAffiliate[_addr], "Address is already an affiliate.");
        require(_addr != address(0), "0x00 address not allowed");
        require(!affiliateCodeExists[_code], "Affiliate code already exists!");
        require(_percentage <= 100 && _percentage > 0, "Percentage must be > 0 && <= 100");
        affiliateCodeExists[_code] = true;
        isAffiliate[_addr] = true;
        affiliateCodeToAddr[_code] = _addr;
        affiliateCodeOfAddr[_addr] = _code;
        commissionPercentage[_code] = _percentage;
        emit NewAffiliatePartnership(_addr,_code);
        return true;
    }


    /**
     * Allows the owner of the contract to set a customised commission percentage for a given affiliate partner.
     * 
     * @param _addressOfAffiliate The wallet address of the affiliate partner.
     * @param _percentage The commission percentage the affiliate will receive.
     * 
     * @return success True if function executes successfully, 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;
    }