// File: contracts/V1/DigiMonkzStaking.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

contract DigiMonkzStaking {
    IERC721 public genesis111;
    IERC721 public genesis2;

    struct NftInfo {
        uint16 tokenId;
        uint256 stakedAt;
        uint256 lastClaimedAt;
        uint256 artifact;
    }
    mapping(uint16 => uint256) public artifactPerGen1Nft;
    mapping(uint16 => uint256) public artifactPerGen2Nft;
    mapping(address => uint256) public artifactPerStaker;
    mapping(address => NftInfo[]) public gen1InfoPerStaker;
    mapping(address => NftInfo[]) public gen2InfoPerStaker;

    event Stake(uint256 indexed tokenId);
    event Unstake(
        uint256 indexed tokenId,
        uint256 stakedAtTimestamp,
        uint256 removedFromStakeAtTimestamp
    );

    constructor(address _gen1Addr, address _gen2Addr) {
        genesis111 = IERC721(_gen1Addr);
        genesis2 = IERC721(_gen2Addr);
    }

    function gen1Stake(uint16 _tokenId) external returns (bool) {
        require(genesis111.ownerOf(_tokenId) == msg.sender);

        uint256 len = gen1InfoPerStaker[msg.sender].length;
        bool flag;
        for (uint256 i = 0; i < len; i++) {
            if (gen1InfoPerStaker[msg.sender][i].tokenId == _tokenId) {
                flag = true;
            }
        }
        require(flag == false);

        genesis111.transferFrom(msg.sender, address(this), _tokenId);

        uint256 artifact = artifactPerGen1Nft[_tokenId];
        NftInfo memory stakingNft = NftInfo(
            _tokenId,
            block.timestamp,
            0,
            artifact
        );
        gen1InfoPerStaker[msg.sender].push(stakingNft);

        emit Stake(_tokenId);

        return true;
    }

    function gen2Stake(uint16 _tokenId) external returns (bool) {
        require(genesis2.ownerOf(_tokenId) == msg.sender);

        uint256 len = gen2InfoPerStaker[msg.sender].length;
        bool flag;
        for (uint256 i = 0; i < len; i++) {
            if (gen2InfoPerStaker[msg.sender][i].tokenId == _tokenId) {
                flag = true;
            }
        }
        require(flag == false);

        genesis2.transferFrom(msg.sender, address(this), _tokenId);

        uint256 artifact = artifactPerGen2Nft[_tokenId];
        NftInfo memory stakingNft = NftInfo(
            _tokenId,
            block.timestamp,
            0,
            artifact
        );
        gen2InfoPerStaker[msg.sender].push(stakingNft);

        emit Stake(_tokenId);

        return true;
    }

    function gen1Unstake(uint16 _tokenId) external returns (bool) {
        require(genesis111.ownerOf(_tokenId) == address(this));

        uint256 len = gen1InfoPerStaker[msg.sender].length;
        require(len != 0);

        uint256 idx = len;
        for (uint256 i = 0; i < len; i++) {
            if (gen1InfoPerStaker[msg.sender][i].tokenId == _tokenId) {
                idx = i;
            }
        }
        require(idx != len);

        genesis111.transferFrom(address(this), msg.sender, _tokenId);

        uint256 stakedTime = gen1InfoPerStaker[msg.sender][idx].stakedAt;
        if (idx != len - 1) {
            gen1InfoPerStaker[msg.sender][idx] = gen1InfoPerStaker[msg.sender][
                len - 1
            ];
        }
        gen1InfoPerStaker[msg.sender].pop();

        emit Unstake(_tokenId, stakedTime, block.timestamp);

        return true;
    }

    function gen2Unstake(uint16 _tokenId) external returns (bool) {
        require(genesis2.ownerOf(_tokenId) == address(this));

        uint256 len = gen2InfoPerStaker[msg.sender].length;
        require(len != 0);

        uint256 idx = len;
        for (uint256 i = 0; i < len; i++) {
            if (gen2InfoPerStaker[msg.sender][i].tokenId == _tokenId) {
                idx = i;
            }
        }
        require(idx != len);
        genesis2.transferFrom(address(this), msg.sender, _tokenId);

        uint256 stakedTime = gen2InfoPerStaker[msg.sender][idx].stakedAt;
        if (idx != len - 1) {
            gen2InfoPerStaker[msg.sender][idx] = gen2InfoPerStaker[msg.sender][
                len - 1
            ];
        }
        gen2InfoPerStaker[msg.sender].pop();

        emit Unstake(_tokenId, stakedTime, block.timestamp);

        return true;
    }

    function getArtifactForGen1(uint16 _tokenId) public returns (uint256) {
        require(genesis111.ownerOf(_tokenId) == address(this));

        uint256 stakedTime;
        uint256 lastClaimedTime;
        uint256 idx;
        uint256 len = gen1InfoPerStaker[msg.sender].length;
        for (uint256 i = 0; i < len; i++) {
            if (gen1InfoPerStaker[msg.sender][i].tokenId == _tokenId) {
                stakedTime = gen1InfoPerStaker[msg.sender][i].stakedAt;
                lastClaimedTime = gen1InfoPerStaker[msg.sender][i]
                    .lastClaimedAt;
                idx = i;
                break;
            }
        }
        require(stakedTime != 0);

        uint256 artifact;
        uint256 period;
        uint256 currentTime = block.timestamp;

        if (_tokenId >= 0 && _tokenId <= 10) {
            period = 12 days;
        } else if (_tokenId >= 11 && _tokenId <= 111) {
            period = 15 days;
        }

        if (lastClaimedTime >= stakedTime) {
            artifact = ((lastClaimedTime - stakedTime) / period);
        } else {
            artifact = (currentTime - stakedTime) / period;
        }
        require(artifact > 0);

        artifactPerGen1Nft[_tokenId] += artifact;
        gen1InfoPerStaker[msg.sender][idx].lastClaimedAt = currentTime;
        gen1InfoPerStaker[msg.sender][idx].artifact += artifact;
        artifactPerStaker[msg.sender] += artifact;

        return artifact;
    }

    function getArtifactForGen2(uint16 _tokenId) public returns (uint256) {
        require(genesis2.ownerOf(_tokenId) == address(this));

        uint256 stakedTime;
        uint256 lastClaimedTime;
        uint256 idx;
        uint256 len = gen2InfoPerStaker[msg.sender].length;
        for (uint256 i = 0; i < len; i++) {
            if (gen2InfoPerStaker[msg.sender][i].tokenId == _tokenId) {
                stakedTime = gen2InfoPerStaker[msg.sender][i].stakedAt;
                lastClaimedTime = gen2InfoPerStaker[msg.sender][i]
                    .lastClaimedAt;
                idx = i;
                break;
            }
        }
        require(stakedTime != 0);

        uint256 artifact;
        uint256 period;
        uint256 currentTime = block.timestamp;

        if (_tokenId >= 1 && _tokenId <= 11) {
            period = 20 days;
        } else {
            period = 30 days;
        }

        if (lastClaimedTime >= stakedTime) {
            artifact = ((lastClaimedTime - stakedTime) / period);
        } else {
            artifact = (currentTime - stakedTime) / period;
        }
        require(artifact > 0);

        artifactPerGen2Nft[_tokenId] += artifact;
        gen2InfoPerStaker[msg.sender][idx].lastClaimedAt = currentTime;
        gen2InfoPerStaker[msg.sender][idx].artifact += artifact;
        artifactPerStaker[msg.sender] += artifact;

        return artifact;
    }

    function claimRewardWithGen1(
        uint256 _numArtifact,
        uint16[] memory _idxArray
    ) external returns (bool) {
        require(artifactPerStaker[msg.sender] >= _numArtifact);

        uint256 sum;
        uint256 len = _idxArray.length;
        uint16 tokenId;
        for (uint256 i = 0; i < len; i++) {
            tokenId = gen1InfoPerStaker[msg.sender][_idxArray[i]].tokenId;
            require(genesis111.ownerOf(tokenId) == address(this));
            sum += artifactPerGen1Nft[tokenId];
            artifactPerGen1Nft[tokenId] = 0;
            gen1InfoPerStaker[msg.sender][_idxArray[i]].artifact = 0;
        }
        require(sum >= _numArtifact);

        artifactPerStaker[msg.sender] -= sum;

        return true;
    }

    function claimRewardWithGen2(
        uint256 _numArtifact,
        uint16[] memory _idxArray
    ) external returns (bool) {
        require(artifactPerStaker[msg.sender] >= _numArtifact);

        uint256 sum;
        uint256 len = _idxArray.length;
        uint16 tokenId;
        for (uint256 i = 0; i < len; i++) {
            tokenId = gen2InfoPerStaker[msg.sender][_idxArray[i]].tokenId;
            require(genesis2.ownerOf(tokenId) == address(this));
            sum += artifactPerGen2Nft[tokenId];
            artifactPerGen2Nft[tokenId] = 0;
            gen2InfoPerStaker[msg.sender][_idxArray[i]].artifact = 0;
        }
        require(sum >= _numArtifact);

        artifactPerStaker[msg.sender] -= sum;

        return true;
    }

    function getGen1StakedArray(
        address _wallet
    ) external view returns (NftInfo[] memory) {
        NftInfo[] memory nftInfo;
        nftInfo = gen1InfoPerStaker[_wallet];
        return nftInfo;
    }

    function getGen2StakedArray(
        address _wallet
    ) external view returns (NftInfo[] memory) {
        NftInfo[] memory nftInfo;
        nftInfo = gen2InfoPerStaker[_wallet];
        return nftInfo;
    }
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @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 `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` 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 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` 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.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must 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 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` 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 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` 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.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @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 the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @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);
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}