// Contract: BaggageClaim
// Target function: function _claimRewards(address user) internal
 `account`.
     */
    function balanceOf(address account) external view returns (uint256);
    
    /**
     * @dev Returns the number of decimal places
     */
    function decimals() external view returns (uint8);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 {
    /**
     * @dev Emitted when `bagId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed bagId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `bagId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed bagId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `bagId` token.
     *
     * Requirements:
     *
     * - `bagId` must exist.
     */
    function ownerOf(uint256 bagId) external view returns (address 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 from,
        address to,
        uint256 bagId
    ) external;

    /**
     * @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 from,
        address to,
        uint256 bagId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `bagId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `bagId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 bagId) external;

    /**
     * @dev Returns the account approved for `bagId` token.
     *
     * Requirements:
     *
     * - `bagId` must exist.
     */
    function getApproved(uint256 bagId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `bagId` token from `from` to `to`.
     *
     * 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 approved 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 from,
        address to,
        uint256 bagId,
        bytes calldata data
    ) external;
}

interface IERC721Metadata {
    function tokenURI(uint256 bagId) external view returns (string memory);
}

contract BaggageClaimData {

    uint256 internal constant PRECISION = 10**18;

    // BAG Info
    address public BAG;
    string public name;
    string public symbol;
    uint256 public lockTime;

    // reward info
    address public rewardToken;
    uint256 public rewardsPerSecond;
    uint256 public lastRewardTime;

    // Governance
    address public lockTimeSetter;

    // Reward Data
    uint256 public dividendsPerBAG;
    uint256 public totalDividends;
    uint256 public numBagsChecked;

    struct UserInfo {
        uint256[] bagIds;
        uint256 balance;
        uint256 totalExcluded;
        uint256 totalRewardsClaimed;
    }

    struct CheckedBagId {
        uint256 index;      // index in user token id array
        uint256 timeLocked; // time the id was locked
        address owner;
    }

    mapping ( address => UserInfo ) public userInfo;
    mapping ( uint256 => CheckedBagId ) public bagInfo;

    uint256 internal constant _NOT_ENTERED = 1;
    uint256 internal constant _ENTERED = 2;
    uint256 internal _status;

    modifier nonReentrant() {
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
        _status = _ENTERED;
        _;
        _status = _NOT_ENTERED;
    }
}

contract BaggageClaim is BaggageClaimData, Cloneable, IERC721, IERC721Metadata {

    function __init__(
        address BAG_,
        address rewardToken_,
        uint256 lockTime_,
        uint256 rewardsPerSecond_,
        string calldata name_,
        string calldata symbol_,
        address lockTimeSetter_
    ) external {

        // ensure data is correct and this function is only called once
        require(
            BAG_ != address(0) &&
            BAG == address(0),
            'Invalid Init'
        );
        require(
            lockTime_ <= 365 days,
            'Lock Time Too Long'
        );

        // set data
        BAG = BAG_;
        rewardToken = rewardToken_;
        lockTime = lockTime_;
        rewardsPerSecond = rewardsPerSecond_;
        name = name_;
        symbol = symbol_;
        lockTimeSetter = lockTimeSetter_;

        // reset reentrancy
        _status = _NOT_ENTERED;
    }

    function setLockTime(uint256 newLockTime) external nonReentrant {
        require(
            msg.sender == lockTimeSetter,
            'Only Setter Can Call'
        );
        require(
            newLockTime <= 365 days,
            'Lock Time Too Long'
        );
        lockTime = newLockTime;
    }

    function setRewardsPerDay(uint256 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; }
        }
    }