// Contract: NFTfiBonusPool
// Target function: function claimBonusByIds(uint256 _pid, uint256[] memory _nftTokenIds ) public nonReentrant
uint256)
    {
        require(
            index < ERC721Enumerable.totalSupply(),
            "ERC721Enumerable: global index out of bounds"
        );
        return _allTokens[index];
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, tokenId);

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
        private
    {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}

abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

contract NFTfiBonusPool is Ownable , ReentrancyGuard{
    using SafeMath for uint256;
    using SafeERC20 for IERC20;


    struct UserInfo {
        address depositUser;
        uint256 nftTokenId;
        uint256 startTime;
        uint256 endTime;

        uint256 lastRewardTime;
        bool inBlackList;
        uint256 rewardReceived; //Reward received
    }

    struct ReceivedInfo {
        uint256 lastRewardTime;
        uint256 rewardReceived; //Reward received
    }

    struct PoolInfo {
        IERC20 lpToken;
        uint256 lpAmount;   //need deposit lptoken amount

        address bonusToken;  //bonus token
        uint256 bonusAmount; //bonus quota
        uint256 bonusPeriod; //release period seconds

        address nftToken;   //check nft proof
        uint256 nftStartId;
        uint256 nftEndId;

        uint256 startTime; //action start time

        uint256 nftCount; //have deposited nft count

        address vaultAddress; //deposit vault address

    }

    // Info of each pool.
    PoolInfo[] public poolInfo;

    // Info of each nft token that stakes LP tokens. [pid, nftid => UserInfo ]
    mapping(uint256 => mapping(uint256 => UserInfo)) public nftIds;

    // Info of each nft token that stakes LP tokens. [pid, nftid => [address => ReceivedInfo] ]
    mapping(uint256 => mapping(uint256 => mapping(address => ReceivedInfo))) public receivedInfos;

    // admin Address
    address public adminAddress;

    event Deposit(address indexed user, uint256 indexed pid, uint256 nftTokenId);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 nftTokenId);
    event ClaimBonus(address indexed user, uint256 indexed pid, uint256 nftTokenId, uint256 amount);
    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);

    event PoolNew(address _lpToken, uint256 _lpAmount, address _bonusToken, uint256 _bonusAmount, uint256 _bonusPeriod, address _nftToken,
        uint256 _nftStartId , uint256 _nftEndId , uint256 _startTime, address _vaultAddress);

    event PoolUpdate(uint256 _pid, address _lpToken, uint256 _lpAmount, address _bonusToken, uint256 _bonusAmount, uint256 _bonusPeriod, address _nftToken,
        uint256 _nftStartId , uint256 _nftEndId , uint256 _startTime, address _vaultAddress);

    constructor()  {
        adminAddress = msg.sender;
    }

    modifier onlyAdmin() {
        require(msg.sender == adminAddress, "admin: wut?");
        _;
    }

    // Update admin address by the previous dev.
    function setAdmin(address _adminAddress) public onlyOwner {
        adminAddress = _adminAddress;
    }

    function setBlackList(uint256 _pid, uint256 _nftTokenId ) public onlyAdmin {
        nftIds[_pid][_nftTokenId].inBlackList = true;
    }

    function removeBlackList(uint256 _pid, uint256 _nftTokenId) public onlyAdmin {
        nftIds[_pid][_nftTokenId].inBlackList = false;
    }

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    // Add a new lp to the pool. Can only be called by the owner.
    // Notice: DO NOT add the same LP token more than once. Rewards will be messed up if you do.
    function add( IERC20 _lpToken, uint256 _lpAmount, address _bonusToken, uint256 _bonusAmount, uint256 _bonusPeriod, address _nftToken,
        uint256 _nftStartId , uint256 _nftEndId , uint256 _startTime, address _vaultAddress ) public onlyAdmin {
        require(address(_lpToken) != address(0), "lpToken is the zero address");

        poolInfo.push(PoolInfo({
            lpToken : _lpToken,
            lpAmount : _lpAmount,
            bonusToken : _bonusToken,
            bonusAmount : _bonusAmount,

            bonusPeriod : _bonusPeriod,
            nftToken : _nftToken,
            nftStartId : _nftStartId,
            nftEndId : _nftEndId,
            startTime : _startTime,
            nftCount : 0,
            vaultAddress : _vaultAddress
        }));

        emit PoolNew( address(_lpToken), _lpAmount, _bonusToken, _bonusAmount, _bonusPeriod, _nftToken, _nftStartId, _nftEndId, _startTime, _vaultAddress);
    }


    function setPool( uint256 _pid, IERC20 _lpToken, uint256 _lpAmount, address _bonusToken, uint256 _bonusAmount, uint256 _bonusPeriod, address _nftToken,
        uint256 _nftStartId , uint256 _nftEndId , uint256 _startTime, address _vaultAddress ) public onlyAdmin {
        require(address(_lpToken) != address(0), "lpToken is the zero address");

        PoolInfo storage pool = poolInfo[_pid];
        pool.lpToken = _lpToken;
        pool.lpAmount = _lpAmount;
        pool.bonusToken = _bonusToken;
        pool.bonusAmount = _bonusAmount;
        pool.bonusPeriod = _bonusPeriod;
        pool.nftToken = _nftToken;
        pool.nftStartId = _nftStartId;
        pool.nftEndId = _nftEndId;
        pool.vaultAddress = _vaultAddress;
        pool.startTime = _startTime;

        emit PoolUpdate(_pid, address(_lpToken), _lpAmount, _bonusToken, _bonusAmount, _bonusPeriod, _nftToken, _nftStartId, _nftEndId, _startTime, _vaultAddress);

    }

    //view the pending reward by nftids
    function pendingBonusByIds(uint256 _pid, uint256[] memory _nftTokenIds ) public view returns (uint256) {
        uint256 pendingReward;
        uint256 len = _nftTokenIds.length;
        for (uint256 i = 0; i < len; i++){
            pendingReward = pendingReward.add( pendingBonus(_pid,_nftTokenIds[i] ) );
        }

        return pendingReward;
    }

    //view the pending reward
    function pendingBonus(uint256 _pid, uint256 _nftTokenId ) public view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = nftIds[_pid][_nftTokenId];

        if( user.nftTokenId == 0 ){
            return 0;
        }

        uint256 checkTime = block.timestamp;
        if( checkTime > user.endTime ){
            checkTime = user.endTime;
        }

        uint256 rewardTime = checkTime.sub( user.lastRewardTime);

        uint256 pendingReward = pool.bonusAmount.mul(rewardTime).div(pool.bonusPeriod);

        return pendingReward;
    }

    //view the Received reward by nftids
    function rewardReceivedByIds(uint256 _pid, address _userAddress, uint256[] memory _nftTokenIds ) public view returns (uint256) {
        uint256 receivedReward;
        uint256 len = _nftTokenIds.length;
        for (uint256 i = 0; i < len; i++){
            ReceivedInfo storage receivedInfo = receivedInfos[_pid][_nftTokenIds[i]][_userAddress];
            receivedReward = receivedReward.add( receivedInfo.rewardReceived );
        }
        return receivedReward;
    }


    // Deposit LP tokens dividends bonus , need check nftTokenId ;
    function deposit(uint256 _pid,  uint256 _nftTokenId ) public nonReentrant {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = nftIds[_pid][_nftTokenId];

        require(!user.inBlackList, "in black list");
        require( user.nftTokenId == 0 , "nft has beed deposited");

        uint256 balance = IERC20( pool.lpToken ).balanceOf( msg.sender );

        require( balance >= pool.lpAmount, "lpToken balance is not enough");

        require( block.timestamp >= pool.startTime, "action is not start.");

        require( pool.nftEndId.add(1).sub(pool.nftStartId) > pool.nftCount, "max nfts deposited." );

        //check nft owner is the sender.
        require( ERC721Enumerable( pool.nftToken ).ownerOf(_nftTokenId) == _msgSender(), "nft is not the owner." );

        if( pool.lpAmount > 0 ){
            pool.lpToken.safeTransferFrom(address(msg.sender), pool.vaultAddress, pool.lpAmount);
        }

        user.depositUser = msg.sender;
        user.nftTokenId = _nftTokenId;
        user.startTime = block.timestamp;
        user.endTime = block.timestamp.add(pool.bonusPeriod);
        user.lastRewardTime = block.timestamp;

        pool.nftCount = pool.nftCount.add(1);

        emit Deposit(msg.sender, _pid, _nftTokenId);
    }

    // Withdraw pool bonus.
    function claimBonus(uint256 _pid, uint256 _nftTokenId ) public{
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = nftIds[_pid][_nftTokenId];
        ReceivedInfo  storage receivedInfo = receivedInfos[_pid][_nftTokenId][msg.sender];

        require( user.nftTokenId > 0 , "nft has not beed deposited");
        require( ERC721Enumerable( pool.nftToken ).ownerOf(_nftTokenId) == _msgSender(), "nft is not the owner." );

        uint256 pendingAmount = pendingBonus(_pid, _nftTokenId);
        if (pendingAmount > 0) {
            IERC20( pool.bonusToken ).transfer(msg.sender, pendingAmount);
            user.rewardReceived = user.rewardReceived.add(pendingAmount);
            receivedInfo.rewardReceived = receivedInfo.rewardReceived.add(pendingAmount);
        }

        user.lastRewardTime = block.timestamp;
        receivedInfo.lastRewardTime = user.lastRewardTime;

        emit ClaimBonus(msg.sender, _pid, _nftTokenId, pendingAmount);
    }