// Contract: BaggageClaim
// Target function: function approve(address, uint256) external override
 rewardsPerDay) external nonReentrant {
        require(
            msg.sender == lockTimeSetter,
            'Only Setter Can Call'
        );
        rewardsPerSecond = rewardsPerDay / 1 days;
    }

    function setLockTimeSetter(address newSetter) external nonReentrant {
        require(
            msg.sender == lockTimeSetter,
            'Only Setter Can Call'
        );
        lockTimeSetter = newSetter;
    }

    function checkBag(uint256 bagId) external nonReentrant {
        _checkBag(bagId);
    }

    function checkMultipleBags(uint256[] calldata bagIds) external nonReentrant {
        _checkMultipleBags(bagIds);
    }

    function pickUpBag(uint256 bagId) external nonReentrant {
        _pickUpBag(bagId);
    }

    function pickUpMultipleBags(uint256[] calldata bagIds) external nonReentrant {
        _pickUpMultipleBags(bagIds);
    }

    function claimRewards() external nonReentrant {
        _updateRewards();
        _claimRewards(msg.sender);
    }

    function updateRewards() external nonReentrant {
        _updateRewards();
    }

    function _initRewards() internal {
        lastRewardTime = block.timestamp;
    }

    function _updateRewards() internal {

        // calculate the time since the last reward was claimed
        uint256 timeSince = timeSinceLastReward();
        if (timeSince == 0) {
            return;
        }

        // calculate the amount of rewards to add
        uint256 toReward = rewardsPerSecond * timeSince;

        // reset the last reward time
        lastRewardTime = block.timestamp;

        // increase rewards
        unchecked {
            totalDividends += toReward;
            dividendsPerBAG += ( toReward * PRECISION ) / numBagsChecked;
        }
    }

    function _checkBag(uint256 bagId) internal {

        // ensure message sender is owner of BAG
        require(
            isOwner(bagId, msg.sender),
            'Sender Not BAG Owner'
        );
        require(
            bagInfo[bagId].owner == address(0),
            'Already Checked'
        );

        // if first bag check, reset reward timer
        if (numBagsChecked == 0) {
            _initRewards();
        } else {
            _updateRewards();
        }

        // claim rewards if applicable
        _claimRewards(msg.sender);    

        // send BAG to self
        IERC721(BAG).transferFrom(msg.sender, address(this), bagId);

        // ensure BAG is now owned by `this`
        require(
            isOwner(bagId, address(this)),
            'BAG Ownership Not Transferred'
        );

        // increment total bags checked and user balance
        unchecked {
            numBagsChecked++;
            userInfo[msg.sender].balance++;
        }

        // reset total rewards
        userInfo[msg.sender].totalExcluded = getCumulativeDividends(userInfo[msg.sender].balance);
        
        // set current bagId index to length of user id array
        bagInfo[bagId].index = userInfo[msg.sender].bagIds.length;
        bagInfo[bagId].timeLocked = block.timestamp;
        bagInfo[bagId].owner = msg.sender;

        // push new token id to user id array
        userInfo[msg.sender].bagIds.push(bagId);

        emit Transfer(address(0), msg.sender, bagId);
    }

    function _checkMultipleBags(uint256[] calldata bagIds) internal {

        // if first bag checked, reset reward timer
        if (numBagsChecked == 0) {
            _initRewards();
        } else {
            _updateRewards();
        }

        // claim rewards if applicable
        _claimRewards(msg.sender);   

        // length of array
        uint256 len = bagIds.length; 

        for (uint i = 0; i < len;) {
            // ensure message sender is owner of BAG
            require(
                isOwner(bagIds[i], msg.sender),
                'Sender Not BAG Owner'
            );
            require(
                bagInfo[bagIds[i]].owner == address(0),
                'Already Checked'
            );

            // send BAG to self
            IERC721(BAG).transferFrom(msg.sender, address(this), bagIds[i]);

            // ensure BAG is now owned by `this`
            require(
                isOwner(bagIds[i], address(this)),
                'BAG Ownership Not Transferred'
            );

            // set current bagId index to length of user id array
            bagInfo[bagIds[i]].index = userInfo[msg.sender].bagIds.length;
            bagInfo[bagIds[i]].timeLocked = block.timestamp;
            bagInfo[bagIds[i]].owner = msg.sender;

            // push new token id to user id array
            userInfo[msg.sender].bagIds.push(bagIds[i]);

            emit Transfer(address(0), msg.sender, bagIds[i]);
            unchecked { ++i; }
        }

        // increment total bags checked and user balance
        numBagsChecked += len;
        userInfo[msg.sender].balance += len;

        // reset total rewards
        userInfo[msg.sender].totalExcluded = getCumulativeDividends(userInfo[msg.sender].balance);
    }

    function _pickUpBag(uint256 bagId) internal {
        require(
            isOwner(bagId, address(this)),
            'BAG Is Not Checked'
        );
        require(
            bagInfo[bagId].owner == msg.sender,
            'Only Owner Can Pick Up Bag'
        );
        require(
            hasCheckedBag(msg.sender, bagId),
            'User Has Not Checked bagId'
        );
        require(
            timeUntilUnlock(bagId) == 0,
            'Token Still Locked'
        );

        // update rewards
        _updateRewards();

        // claim pending rewards if any
        _claimRewards(msg.sender);
        
        // decrement balance
        userInfo[msg.sender].balance -= 1;
        numBagsChecked -= 1;

        // reset total rewards
        userInfo[msg.sender].totalExcluded = getCumulativeDividends(userInfo[msg.sender].balance);

        // remove BAG from user array
        _removeBAG(msg.sender, bagId);
        
        // send BAG to caller
        IERC721(BAG).transferFrom(address(this), msg.sender, bagId);

        emit Transfer(msg.sender, address(0), bagId);
    }

    function _pickUpMultipleBags(uint256[] calldata bagIds) internal {

        // update rewards
        _updateRewards();

        // claim pending rewards if any
        _claimRewards(msg.sender);

        // length of array
        uint256 len = bagIds.length;

        // decrement balance
        userInfo[msg.sender].balance -= len;
        numBagsChecked -= len;

        // reset total rewards
        userInfo[msg.sender].totalExcluded = getCumulativeDividends(userInfo[msg.sender].balance);

        for (uint i = 0; i < len;) {
            
            require(
                isOwner(bagIds[i], address(this)),
                'BAG Is Not Checked'
            );
            require(
                bagInfo[bagIds[i]].owner == msg.sender,
                'Only Owner Can Pick Up Bag'
            );
            require(
                hasCheckedBag(msg.sender, bagIds[i]),
                'User Has Not Checked bagId'
            );
            require(
                timeUntilUnlock(bagIds[i]) == 0,
                'Token Still Locked'
            );

            // remove BAG from user array
            _removeBAG(msg.sender, bagIds[i]);

            // send BAG to caller
            IERC721(BAG).transferFrom(address(this), msg.sender, bagIds[i]);

            // emit event
            emit Transfer(msg.sender, address(0), bagIds[i]);

            unchecked { ++i; }
        }
    }

    /**
        Claims Reward For User
     */
    function _claimRewards(address user) internal {

        // return if zero balance
        if (userInfo[user].balance == 0) {
            return;
        }

        // fetch pending rewards
        uint pending = pendingRewards(user);
        uint max = rewardBalanceOf();
        if (pending > max) {
            pending = max;
        }
        
        // reset total rewards
        userInfo[user].totalExcluded = getCumulativeDividends(userInfo[user].balance);

        // return if no rewards
        if (pending == 0) {
            return;
        }

        // incremenet total rewards claimed
        unchecked {
            userInfo[user].totalRewardsClaimed += pending;
        }

        // transfer reward to user
        if (rewardToken == address(0)) {
            TransferHelper.safeTransferETH(user, pending);
        } else {
            TransferHelper.safeTransfer(rewardToken, user, pending);
        }
    }

    function _removeBAG(address user, uint256 bagId) internal {
        
        uint lastElement = userInfo[user].bagIds[userInfo[user].bagIds.length - 1];
        uint removeIndex = bagInfo[bagId].index;

        userInfo[user].bagIds[removeIndex] = lastElement;
        bagInfo[lastElement].index = removeIndex;
        userInfo[user].bagIds.pop();

        delete bagInfo[bagId];
    }

    /**
        Pending Token Rewards For `account` based on the last time _updateRewards() was called
     */
    function pendingRewards(address account) public view returns (uint256) {
        if(userInfo[account].balance == 0){ return 0; }

        uint256 accountTotalDividends = getCumulativeDividends(userInfo[account].balance);
        uint256 accountTotalExcluded = userInfo[account].totalExcluded;

        return accountTotalDividends <= accountTotalExcluded ? 0 : accountTotalDividends - accountTotalExcluded;
    }

    /**
        Pending rewards including the current state of _updateRewards()
        This result will match the actual payout of claimRewards() assuming the same timestamp, unless:
            - `rewardToken` is a tax on transfer token
            - insufficient `rewardToken`s are supplied by contract owner
     */
    function currentPendingRewards(address account) external view returns (uint256) {
        if(userInfo[account].balance == 0){ return 0; }

        // calculate the time since the last reward was claimed
        uint256 timeSince = timeSinceLastReward();
        if (timeSince == 0) {
            return 0;
        }

        // calculate the amount of rewards to add
        uint256 toReward = rewardsPerSecond * timeSince;

        // simulate the new dividends per BAG value
        uint256 dividendsPerBAGCurrent = dividendsPerBAG + ( ( toReward * PRECISION ) / numBagsChecked );

        // return the expected amount to receive
        uint256 accountTotalDividends = ( userInfo[account].balance * dividendsPerBAGCurrent ) / PRECISION;
        uint256 accountTotalExcluded = userInfo[account].totalExcluded;
        return accountTotalDividends <= accountTotalExcluded ? 0 : accountTotalDividends - accountTotalExcluded;
    }

    function timeSinceLastReward() public view returns (uint256) {
        if (lastRewardTime == 0 || numBagsChecked == 0) {
            return 0;
        }
        return block.timestamp > lastRewardTime ? block.timestamp - lastRewardTime : 0;
    }

    /**
        Cumulative Dividends For A Number Of Tokens
     */
    function getCumulativeDividends(uint256 share) internal view returns (uint256) {
        return (share * dividendsPerBAG) / PRECISION;
    }

    function timeUntilUnlock(uint256 bagId) public view returns (uint256) {
        uint unlockTime = bagInfo[bagId].timeLocked + lockTime;
        return unlockTime <= block.timestamp ? 0 : unlockTime - block.timestamp;
    }

    function isOwner(uint256 bagId, address user) public view returns (bool) {
        return IERC721(BAG).ownerOf(bagId) == user;
    }

    function listUserCheckedBAGs(address user) public view returns (uint256[] memory) {
        return userInfo[user].bagIds;
    }

    function fetchBalancePendingAndTotalRewards(address user) public view returns (uint256, uint256, uint256) {
        return (userInfo[user].balance, pendingRewards(user), userInfo[user].totalRewardsClaimed);
    }
    
    function listUserCheckedBAGsAndURIs(address user) public view returns (uint256[] memory, string[] memory) {
        
        uint len = userInfo[user].bagIds.length;
        string[] memory uris = new string[](len);
        for (uint i = 0; i < len;) {
            uris[i] = IERC721Metadata(BAG).tokenURI(userInfo[user].bagIds[i]);
            unchecked {
                ++i;
            }
        }
        return (userInfo[user].bagIds, uris);
    }

    function listUserCheckedBAGsURIsAndRemainingLockTimes(address user) public view returns (
        uint256[] memory, 
        string[] memory,
        uint256[] memory
    ) {
        
        uint len = userInfo[user].bagIds.length;
        string[] memory uris = new string[](len);
        uint256[] memory remainingLocks = new uint256[](len);
        for (uint i = 0; i < len;) {
            uris[i] = IERC721Metadata(BAG).tokenURI(userInfo[user].bagIds[i]);
            remainingLocks[i] = timeUntilUnlock(userInfo[user].bagIds[i]);
            unchecked {
                ++i;
            }
        }
        return (userInfo[user].bagIds, uris, remainingLocks);
    }

    function listUserTotalBAGs(address user, uint min, uint max) public view returns (uint256[] memory) {
        
        IERC721 BAG_ = IERC721(BAG);
        uint len = BAG_.balanceOf(user);

        uint256[] memory ids = new uint256[](len);
        uint count = 0;

        for (uint i = min; i < max;) {

            if (BAG_.ownerOf(i) == user) {
                ids[count] = i;
                count++;
            }
            
            unchecked {++i;}
        }
        return (ids);
    }

    function listUserTotalBAGsAndUris(address user, uint min, uint max) public view returns (uint256[] memory, string[] memory) {
        
        IERC721 BAG_ = IERC721(BAG);
        uint len = BAG_.balanceOf(user);

        uint256[] memory ids = new uint256[](len);
        string[] memory uris = new string[](len);
        uint count = 0;

        for (uint i = min; i < max;) {

            if (BAG_.ownerOf(i) == user) {
                ids[count] = i;
                uris[count] = IERC721Metadata(BAG).tokenURI(i);
                count++;
            }
            
            unchecked {++i;}
        }
        return (ids, uris);
    }

    function hasCheckedBag(address user, uint256 bagId) public view returns (bool) {
        if (userInfo[user].bagIds.length <= bagInfo[bagId].index || bagInfo[bagId].owner != user) {
            return false;
        }
        return userInfo[user].bagIds[bagInfo[bagId].index] == bagId;
    }

    function hasCheckedBags(address user, uint256[] calldata bagId) public view returns (bool[] memory) {
        uint len = bagId.length;
        bool[] memory hasChecked = new bool[](len);
        for (uint i = 0; i < len;) {
            hasChecked[i] = userInfo[user].bagIds[bagInfo[bagId[i]].index] == bagId[i];
            unchecked {
                ++i;
            }
        }
        return hasChecked;
    }

    function rewardBalanceOf() public view returns (uint256) {
        return rewardToken == address(0) ? address(this).balance : IERC20(rewardToken).balanceOf(address(this));
    }

    function totalSupply() public view returns (uint256) {
        return IERC721(BAG).balanceOf(address(this));
    }

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view override returns (uint256 balance) {
        return userInfo[owner].balance;
    }

    /**
     * @dev Returns the owner of the `bagId` token.
     *
     * Requirements:
     *
     * - `bagId` must exist.
     */
    function ownerOf(uint256 bagId) external view override returns (address owner) {
        return bagInfo[bagId].owner;
    }

    /**
     * @dev Safely transfers `bagId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `bagId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address,
        address,
        uint256
    ) external override {

    }

    /**
     * @dev Transfers `bagId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `bagId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address,
        address,
        uint256
    ) external override {

    }