contract TimelockERC721 is Ownable {
    event TLCERC721New(
        bytes32 indexed contractId,
        address indexed sender,
        address tokenContract,
        uint256 tokenId,
        uint256 timelock
    );

    event TLCERC721Withdraw(bytes32 indexed contractId);

    struct LockContract {
        address sender;
        address tokenContract;
        uint256 tokenId;
        // locked UNTIL this time. Unit depends on consensus algorithm.
        // PoA, PoA and IBFT all use seconds. But Quorum Raft uses nano-seconds
        uint256 timelock;
        bool withdrawn;
    }

    modifier tokensTransferable(address _token, uint256 _tokenId) {
        // ensure this contract is approved to transfer the designated token
        // so that it is able to honor the claim request later
        require(
            ERC721(_token).getApproved(_tokenId) == address(this),
            "The TLC must have been designated an approved spender for the tokenId"
        );
        _;
    }
    modifier futureTimelock(uint256 _time) {
        // only requirement is the timelock time is after the last blocktime (block.timestamp).
        // probably want something a bit further in the future then this.
        // but this is still a useful sanity check:
        require(_time > block.timestamp, "timelock time must be in the future");
        _;
    }
    modifier contractExists(bytes32 _contractId) {
        require(haveContract(_contractId), "contractId does not exist");
        _;
    }
    modifier withdrawable(bytes32 _contractId) {
        require(
            contracts[_contractId].sender == msg.sender,
            "withdrawable: not sender"
        );
        require(
            contracts[_contractId].withdrawn == false,
            "withdrawable: already withdrawn"
        );
        require(
            contracts[_contractId].timelock <= block.timestamp,
            "withdrawable: timelock not yet passed"
        );
        _;
    }
    modifier feesCollectable(bytes32 _contractId) {
        require(
            contracts[_contractId].sender == msg.sender,
            "feesCollectable: not sender"
        );
        require(
            contracts[_contractId].withdrawn == false,
            "feesCollectable: already withdrawn"
        );
        _;
    }

    mapping(bytes32 => LockContract) contracts;

    /**
     * @dev Sender sets up a new time lock contract depositing the
     * funds.
     *
     * @param _timelock UNIX epoch seconds time that the lock expires at.
     *                  Withdraws can be made after this time.
     * @param _tokenContract ERC20 Token contract address.
     * @param _tokenId Id of the token to lock up.
     * @return contractId Id of the new TLC. This is needed for subsequent
     *                    calls.
     */
    function newContract(
        uint256 _timelock,
        address _tokenContract,
        uint256 _tokenId
    )
        external
        onlyOwner
        tokensTransferable(_tokenContract, _tokenId)
        futureTimelock(_timelock)
        returns (bytes32 contractId)
    {
        contractId = sha256(
            abi.encodePacked(msg.sender, _tokenContract, _tokenId, _timelock)
        );

        // Reject if a contract already exists with the same parameters. The
        // sender must change one of these parameters
        if (haveContract(contractId)) revert("Contract already exists");

        // This contract becomes the temporary owner of the token
        ERC721(_tokenContract).transferFrom(
            msg.sender,
            address(this),
            _tokenId
        );

        contracts[contractId] = LockContract(
            msg.sender,
            _tokenContract,
            _tokenId,
            _timelock,
            false
        );

        emit TLCERC721New(
            contractId,
            msg.sender,
            _tokenContract,
            _tokenId,
            _timelock
        );
    }

    /**
     * @dev Collect Uniswap V3 LP fees securely while still under ownership of the time lock contract.
     * @param _contractId TLC contract id
     */
    function collectFees(
        bytes32 _contractId,
        address recipient,
        uint128 amount0Max,
        uint128 amount1Max
    ) external contractExists(_contractId) feesCollectable(_contractId) {
        LockContract memory c = contracts[_contractId];

        INonfungiblePositionManager nonfungiblePositionManager = INonfungiblePositionManager(
                c.tokenContract
            );

        nonfungiblePositionManager.collect(
            INonfungiblePositionManager.CollectParams({
                tokenId: c.tokenId,
                recipient: recipient,
                amount0Max: amount0Max,
                amount1Max: amount1Max
            })
        );
    }

    /**
     * @dev Called by the sender if the time lock has expired.
     * This will restore ownership of the tokens to the sender.
     *
     * @param _contractId Id of TLC to return from.
     * @return bool true on success
     */
    function withdraw(bytes32 _contractId)
        external
        contractExists(_contractId)
        withdrawable(_contractId)
        returns (bool)
    {
        LockContract storage c = contracts[_contractId];
        c.withdrawn = true;
        ERC721(c.tokenContract).transferFrom(
            address(this),
            c.sender,
            c.tokenId
        );
        emit TLCERC721Withdraw(_contractId);
        return true;
    }

    /**
     * @dev Get contract details.
     * @param _contractId TLC contract id
     */
    function getContract(bytes32 _contractId)
        public
        view
        returns (
            address sender,
            address tokenContract,
            uint256 tokenId,
            uint256 timelock,
            bool withdrawn
        )
    {
        if (haveContract(_contractId) == false)
            return (address(0), address(0), 0, 0, false);
        LockContract memory c = contracts[_contractId];
        return (c.sender, c.tokenContract, c.tokenId, c.timelock, c.withdrawn);
    }

    /**
     * @dev Is there a contract with id _contractId.
     * @param _contractId Id into contracts mapping.
     */
    function haveContract(bytes32 _contractId)
        internal
        view
        returns (bool exists)
    {
        exists = (contracts[_contractId].sender != address(0));
    }
}
/**
 * @title Timelock Contracts on Ethereum ERC721 tokens.
 *
 * This contract provides a way to create and keep Timelock Contracts for ERC721 tokens.
 * In addition, it contains a collectFees function for securely collecting Liquidity Pool fees
 * from Uniswap V3 NonfungiblePositionManger while still under timelock.
 *
 *
 * Protocol:
 *
 *  1) newContract(timelock, tokenContract, tokenId) - a
 *      sender calls this to create a new TLC on a given token (tokenContract)
 *       for a given token ID. A 32 byte contract id is withdrawn
 *  3) withdraw() - after timelock has expired the sender / creator of the TLC can get their tokens
 *      back with this function.
 */
function collectFees(
    bytes32 _contractId,
    address recipient,
    uint128 amount0Max,
    uint128 amount1Max
) external contractExists(_contractId) feesCollectable(_contractId) {
    LockContract memory c = contracts[_contractId];

    INonfungiblePositionManager nonfungiblePositionManager = INonfungiblePositionManager(
            c.tokenContract
        );

    nonfungiblePositionManager.collect(
        INonfungiblePositionManager.CollectParams({
            tokenId: c.tokenId,
            recipient: recipient,
            amount0Max: amount0Max,
            amount1Max: amount1Max
        })
    );
}

/**
 * @dev Collect Uniswap V3 LP fees securely while still under ownership of the time lock contract.
 * @param _contractId TLC contract id
 */