contract TokensSaleReserver is Ownable, Pausable {

    using SafeMath for uint256;

    // Reservation start timestamp
    uint _saleStartTs;
    // Reservation end timestamp
    uint _saleEndTs;

    // RBLS token reservation price
    uint256 private _tokenPrice = 352300;

    // Limit of max amount of RBLS tokens that is allowed to reserve for users that holds less or equal then {_rbNumbersPriceThreshold} Rebel Bots tokens
    uint256 private _plainRbHolderTokensLimit = 250000000000;
    // Limit of max amount of RBLS tokens that is allowed to reserve for users that holds more then {_rbNumbersPriceThreshold} Rebel Bots tokens
    uint256 private _majorRbHoldersTokensLimit = 750000000000;
    // Threshold of the owned Rebel Bots NFTs that regulates limit of the RBLS tokens that is possible to reserve
    uint256 private _rbNumbersPriceThreshold = 5;
    // Snapshot of the RebelBots balance per each holder wallet
    mapping(address => uint256) private _rebelBotsBalances;

    // Array with all buyers addresses, used for enumeration
    address[] private _allBuyers;

    struct AirdropData {
        address receiver;
        uint256 amount;
    }

    // Mapping from buyer address array of airdrop address and appropriate number of reserved RBLS tokens
    mapping(address => AirdropData[]) private airdropsDataSet;

    /**
     * @dev Emitted when `buyer` reserves 'tokensNumber' RBLS tokens
    */
    event TokensSell(
        address indexed buyer,
        address airdropAddress,
        uint tokensNumber,
        uint256 rbOwnedNumber
    );

    constructor(uint saleStartTs, uint saleEndTs) {
        _saleStartTs = saleStartTs;
        _saleEndTs = saleEndTs;
    }

    /**
     * @dev updates limits of RBLS tokens allowed for the reservation
    */
    function updateLimits(uint256 plainRbHolderTokensLimit, uint256 majorRbHoldersTokensLimit, uint rbNumbersPriceThreshold) public onlyOwner {
        require(plainRbHolderTokensLimit >= 0, "plainRbHolderTokensLimit should be positive");
        require(majorRbHoldersTokensLimit >= 0, "majorRbHoldersTokensLimit should be positive");
        require(rbNumbersPriceThreshold > 0, "rbNumbersPriceThreshold should be positive");
        _plainRbHolderTokensLimit = plainRbHolderTokensLimit;
        _majorRbHoldersTokensLimit = majorRbHoldersTokensLimit;
        _rbNumbersPriceThreshold = rbNumbersPriceThreshold;
    }

    /**
     * @dev updates sale start and sale end dates
    */
    function updateSalePeriod(uint saleStartTs, uint saleEndTs) public onlyOwner {
        require(saleStartTs >= 0, "plainRbHolderTokensLimit should be positive");
        require(saleEndTs > saleStartTs, "saleEndTs should be greater then saleStartTs");
        _saleStartTs = saleStartTs;
        _saleEndTs = saleEndTs;
    }

    /**
      * @dev updates RBLS token reservation price
     */
    function updatePrice(uint256 tokenPrice) public onlyOwner {
        require(tokenPrice >= 0, "tokenPrice should be positive");
        _tokenPrice = tokenPrice;
    }

    /**
      * @dev get the RBLS token reservation price
     */
    function getPrice() public view returns(uint256) {
        return _tokenPrice;
    }

    /**
     * @dev returns the maximum possible amount of RBLS tokens that is allowed to reserve for 'rbHolder' address
    */
    function getMaxTokensBuyLimit(address rbHolder) public view returns (uint256) {
        uint256 rbTokensBalance = getRebelBotsHolderBalance(rbHolder);

        return getMaxTokensBuyLimit(rbHolder, rbTokensBalance);
    }

    /**
     * @dev returns the maximum possible amount of RBLS tokens that is allowed to reserve for 'rbHolder' address
     * 'rbTokensBalance' - balance of th Rebel Bots NFT tokens of the 'rbHolder' address
    */
    function getMaxTokensBuyLimit(address rbHolder, uint256 rbTokensBalance) private view returns (uint256) {
        uint256 totalTokensLimit;
        if (rbTokensBalance == 0) {
            return 0;
        } else if (rbTokensBalance <= _rbNumbersPriceThreshold) {
            totalTokensLimit = _plainRbHolderTokensLimit;
        } else {
            totalTokensLimit = _majorRbHoldersTokensLimit;
        }
        uint256 reservedTokensNumber = getTotalReservedTokens(rbHolder);
        if (reservedTokensNumber >= totalTokensLimit) {
            return 0;
        }
        return totalTokensLimit.sub(reservedTokensNumber);
    }

    /**
     * @dev returns the total amount of RBLS tokens that were reserved by 'buyer'
    */
    function getTotalReservedTokens(address buyer) public view returns (uint256) {
        AirdropData[] memory buyerAirdropData = airdropsDataSet[buyer];
        uint256 totalTokens = 0;
        for (uint i = 0; i < buyerAirdropData.length; i++) {
            AirdropData memory ai = buyerAirdropData[i];
            totalTokens = totalTokens + ai.amount;
        }
        return totalTokens;
    }

    /**
     * @dev reserves 'tokensNumber' RBLS tokens for the airdrop to the 'airdropAddress' address
    */
    function reserveTokens(uint256 tokensNumber, address airdropAddress) whenNotPaused public payable {
        require(airdropAddress != address(this) && airdropAddress != address(0), "Incorrect airdrop address");
        require(_tokenPrice.mul(tokensNumber) == msg.value, "Ether value sent is incorrect");
        require(block.timestamp >= _saleStartTs && block.timestamp <= _saleEndTs, "Token sale is not available now");

        address buyer = _msgSender();
        uint256 rbTokensBalance = getRebelBotsHolderBalance(buyer);
        uint256 maxTokensBuyLimit = getMaxTokensBuyLimit(buyer, rbTokensBalance);

        require(tokensNumber <= maxTokensBuyLimit, "Tokens number exceeds the allowed number to reserve");

        if (airdropsDataSet[buyer].length == 0) {
            _allBuyers.push(buyer);
        }
        airdropsDataSet[buyer].push(AirdropData(airdropAddress, tokensNumber));

        emit TokensSell(buyer, airdropAddress, tokensNumber, rbTokensBalance);
    }


    /**
     * @dev returns airdrop address for RBLS token for certain buyer address
    */
    function getBuyerReservationsCount(address buyer) public view returns (uint256) {
        return airdropsDataSet[buyer].length;
    }

    /**
     * @dev returns airdrop address for RBLS token for certain buyer address
    */
    function getBuyerReservationByIndex(address buyer, uint256 index) public view returns (AirdropData memory) {
        return airdropsDataSet[buyer][index];
    }

    /**
    * @dev returns total count of addresses that made the reservation
    */
    function buyersCount() public view returns (uint256) {
        return _allBuyers.length;
    }

    /**
    * @dev returns buyer address at a given `index` of all the reservation addresses
    */
    function buyerByIndex(uint256 index) public view returns (address) {
        return _allBuyers[index];
    }

    /**
    * @dev returns number of RB tokens on the snapshot
    */
    function getRebelBotsHolderBalance(address holder) public view returns(uint) {
        return _rebelBotsBalances[holder];
    }

    /**
    * @dev adds a batch of the RB holder data
    */
    function addRebelBotsHoldersBalancesBatch(address[] memory holders, uint[] memory balances) public onlyOwner {
        require(holders.length == balances.length, "The arrays should be wth the same length");
        for (uint i = 0; i < holders.length; i++) {
            _rebelBotsBalances[holders[i]] = balances[i];
        }
    }

    /**
    * @dev withdraws contract balance
    */
    function withdraw() public onlyOwner {
        uint balance = address(this).balance;
        payable(msg.sender).transfer(balance);
    }

    function pause() public onlyOwner {
        _pause();
    }

    function unpause() public onlyOwner {
        _unpause();
    }
}
/**
 * @dev Contract that allows users who holds Rebel Bots NFTs, when the sale is open, to buy the reservation of the RBLS tokens,
 * based on the amount of Rebel Bots in the wallet. Contract accept ETH payments for this operation and stores the data about
 * the buyer, tokens number, and address for the RBLS token receiving ('airdrop' address on Polygon network) in the blockchain.
 *
 * After the sale is closed, appropriate amounts of RBLS token will be sent to each buyer to their airdrop addresses
 * on the Polygon network.
 */
function buyerByIndex(uint256 index) public view returns (address) {
    return _allBuyers[index];
}

/**
 * @dev returns buyer address at a given `index` of all the reservation addresses
 */