// Contract: CicadasNFT
// Target function: function earlyAdopterMint(uint256 mintAmount, uint256 earlyAdopterTokenId) public payable nonReentrant
 }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @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` and `to` are never both zero.
     *
     * 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 {}
}

abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (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();
    }
}

contract ERC721CappedSale is ERC721Enumerable, Ownable, ReentrancyGuard {

    uint256 public _cap;
    uint256 public _maxBuyAmount;
    uint256 public _pricePerToken; // in wei
    address payable public _wallet;

    bool private _isSalePaused = false;


    constructor(
        string memory name_,
        string memory symbol_,
        uint256 initCap,
        uint256 initMaxBuyAmount,
        uint256 initPricePerToken,
        address payable initWallet
    ) ERC721(
        name_,
        symbol_
    ) {
        _cap = initCap;
        _maxBuyAmount = initMaxBuyAmount;
        _pricePerToken = initPricePerToken;
        _wallet = initWallet;
        _isSalePaused = true;
    }


    function mint(uint256 mintAmount) public payable nonReentrant {
        require(!isSalePaused(), "ERC721CappedSale: sale is paused");
        require(mintAmount > 0, "ERC721CappedSale: buy at least 1 NFT");
        require(mintAmount <= _maxBuyAmount, "ERC721CappedSale: its not allowed to buy this much");
        require(mintAmount <= nftsAvailable(), "ERC721CappedSale: not enough NFTs available");
        require((_pricePerToken * mintAmount) == msg.value, "ERC721CappedSale: exact value in ETH needed");

        for (uint256 i = 0; i < mintAmount; i++) {
            _mintToken(_msgSender());
        }
        payable(_wallet).transfer(msg.value);
    }


    function nftsAvailable() public view returns(uint256) {
        return _cap - totalSupply();
    }

    function cap() public view returns(uint256) {
        return _cap;
    }

    function isSalePaused() public view returns(bool) {
        return _isSalePaused;
    }


    function pauseSale() external onlyOwner {
        _isSalePaused = true;
    }

    function resumeSale() external onlyOwner {
        _isSalePaused = false;
    }

    /**
     * should not be necccesarry as the payed ETH are forwarded on minting
     **/
    function emergencyWithdraw() public onlyOwner {
        payable(msg.sender).transfer(address(this).balance);
    }

    /**
     * admin can mint for giveaways, airdrops etc
     **/
    function adminMint(uint256 mintAmount) public onlyOwner {
        require(mintAmount > 0, "ERC721CappedSale: buy at least 1 NFT");
        require(mintAmount <= nftsAvailable(), "ERC721CappedSale: not enough NFTs available");
        for (uint256 i = 0; i < mintAmount; i++) {
            _mintToken(_msgSender());
        }
    }


    function _mintToken(address destinationAddress) internal {
        uint256 newTokenID = totalSupply();
        require(!_exists(newTokenID), "ERC721CappedSale: Token already exist.");
        _safeMint(destinationAddress, newTokenID);
    }
}


contract CicadasNFT is ERC721CappedSale {
    using Strings for uint256;

    string private constant INIT__NFT_NAME = 'Cicadas';
    string private constant INIT__NFT_SYMBOL = 'CICADAS';
    string private constant INIT__UNREVEAL_URI = 'ipfs://QmYm4WThc5yCApjFTw8bCv5uCSfikheyKko6khSpAxPHPQ';
    uint256 private constant INIT__CAP = 10000;
    uint256 private constant INIT__MAX_BUY_AMOUNT = 20;
    uint256 private constant INIT__PRICE_PER_TOKEN = 10**17;



    // update that later
    address payable private constant INIT__WALLET = payable(0x10E7644e76Dad3684c65946afA762f1d2ff098cD);
    IERC721 private constant INIT_EA_NFT = IERC721(0xD1CDf1B4784fa299fECef87096E167a48c8BA042);

    IERC721 public _earlyAdopterNFT;
    uint256 public _earlyAdopterTime;

    bool public _isRevealed = false;
    string public _revealedTokenURI;

    uint256 public _idShift = 0;
    bool public _idShiftDone = false;

    bool public _eaSaleIsDone = false;

    // Mapping from early adopter token ids to early minted nfts
    mapping(uint256 => uint256) private _earlyAdoptersMinted;

    string private _tokenBaseURI = 'ipfs://QmRdCWCYG2NyhKDLoHrLqLvBUUy4MrNeCM8br4UhxzSLsK/';

    constructor(
    ) ERC721CappedSale(
        INIT__NFT_NAME,
        INIT__NFT_SYMBOL,
        INIT__CAP,
        INIT__MAX_BUY_AMOUNT,
        INIT__PRICE_PER_TOKEN,
        payable(msg.sender)  // update that later
    )
    {
        _earlyAdopterNFT = INIT_EA_NFT;
    }


    /**
     * @dev override ERC721
     **/
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        if(!_isRevealed) {
            return INIT__UNREVEAL_URI;
        }
        string memory baseURI = _baseURI();
        uint256 shiftedTokenId = (tokenId+_idShift) % INIT__CAP;
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, shiftedTokenId.toString(), string('.json'))) : "";
    }