// Contract: Form
// Target function: function tokenURI(uint256 tokenId) override public view returns (string memory)
    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(to).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 {}
}







/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}


/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
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();
    }
}

/**
* Full Form and metadata transparently queryable and composable on chain
*/

contract Form is ERC721Enumerable, ReentrancyGuard, Ownable {
    
    struct Canvas {
        string[17] line;
        string metaDesc;
        bool isPainted;
    }
    
    Canvas[] private form;
    uint256 private maxLineLen = 35;
    uint256 private maxMetaDescLen = 280;
    
    function addForm(Canvas memory inputCanvas) private {
        require(getNumForm() < 10000, "Form is final");
        form.push(inputCanvas);
    }
    
    function getFormLine(uint256 tokenId, uint256 lineNum) public view returns (string memory) {
        require(tokenId > 0 && tokenId <= form.length, "Form has yet to enter the collective consciousness");
        require(lineNum > 0 && lineNum <= 17, "An ideal form has a max of 17 lines");
        string memory formLine = form[tokenId - 1].line[lineNum - 1];
        return formLine;
    }
    
    function getForm(uint256 tokenId) public view returns (string memory) {
        require(tokenId > 0 && tokenId <= form.length, "Form has yet to enter the collective consciousness");
        
        string memory fullForm = string(abi.encodePacked(getFormLine(tokenId,1), getFormLine(tokenId,2), getFormLine(tokenId,3), getFormLine(tokenId,4), getFormLine(tokenId,5), getFormLine(tokenId,6), getFormLine(tokenId,7)));
        fullForm = string(abi.encodePacked(fullForm, getFormLine(tokenId,8), getFormLine(tokenId,9), getFormLine(tokenId,10), getFormLine(tokenId,11), getFormLine(tokenId,12), getFormLine(tokenId,13)));
        fullForm = string(abi.encodePacked(fullForm, getFormLine(tokenId,14), getFormLine(tokenId,15), getFormLine(tokenId,16), getFormLine(tokenId,17)));
        
        return fullForm;
    }
    
    function getMetaDesc(uint256 tokenId) public view returns (string memory) {
        require(tokenId > 0 && tokenId <= form.length, "Form has yet to enter the collective consciousness");
        return form[tokenId - 1].metaDesc;
    }
    
    // the current Form owner may always wield the metadata
    function setMetaDesc(uint256 tokenId, string memory metadataDescription) public {
        require(_msgSender() == super.ownerOf(tokenId), "It is another's impression to make");
        require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toString(maxMetaDescLen), " bytes")));
        form[tokenId - 1].metaDesc = metadataDescription;
    }
    
    function getNumForm() public view returns (uint256 numForms) {
        return form.length;
    }
    
    function isPainted(uint256 tokenId) public view returns (bool painted) {
        return form[tokenId - 1].isPainted;
    }
    
    // a subsequently immutable Form
    function mintForm(string[17] memory line, string memory metadataDescription) public nonReentrant onlyOwner {
        require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen && 
        bytes(line[4]).length <= maxLineLen && bytes(line[5]).length <= maxLineLen && bytes(line[6]).length <= maxLineLen && bytes(line[7]).length <= maxLineLen && 
        bytes(line[8]).length <= maxLineLen && bytes(line[9]).length <= maxLineLen && bytes(line[10]).length <= maxLineLen && bytes(line[11]).length <= maxLineLen &&
        bytes(line[12]).length <= maxLineLen && bytes(line[13]).length <= maxLineLen && bytes(line[14]).length <= maxLineLen && bytes(line[15]).length <= maxLineLen && 
        bytes(line[16]).length <= maxLineLen, string(abi.encodePacked("Each line may only contain ", toString(maxLineLen), " bytes")));
        require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toString(maxMetaDescLen), " bytes")));
        
        _safeMint(_msgSender(), getNumForm() + 1);
        addForm(Canvas(line, metadataDescription, true));
    }
    
    // a blank Canvas
    function mintCanvas(string memory metadataDescription) public nonReentrant onlyOwner {
        _safeMint(_msgSender(), form.length + 1);
        string[17] memory lines;
        Canvas memory inputCanvas = Canvas(lines, metadataDescription, false);
        addForm(inputCanvas);
    }
    
    /** one may paint a blank Canvas
    * with immutable ink
    * for history and the evolution of the collective consciousness */
    function paintCanvas(uint256 tokenId, string[17] memory line, string memory metadataDescription) public nonReentrant {
        require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen && 
        bytes(line[4]).length <= maxLineLen && bytes(line[5]).length <= maxLineLen && bytes(line[6]).length <= maxLineLen && bytes(line[7]).length <= maxLineLen && 
        bytes(line[8]).length <= maxLineLen && bytes(line[9]).length <= maxLineLen && bytes(line[10]).length <= maxLineLen && bytes(line[11]).length <= maxLineLen &&
        bytes(line[12]).length <= maxLineLen && bytes(line[13]).length <= maxLineLen && bytes(line[14]).length <= maxLineLen && bytes(line[15]).length <= maxLineLen && 
        bytes(line[16]).length <= maxLineLen, string(abi.encodePacked("Each line may only contain ", toString(maxLineLen), " bytes")));
        require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toString(maxMetaDescLen), " bytes")));
        require(form[tokenId - 1].isPainted == false, "Form is no longer canvas");
        require(_msgSender() == super.ownerOf(tokenId), "It is another's impression to make");
        
        form[tokenId - 1].line = line;
        form[tokenId - 1].metaDesc = metadataDescription; 
        form[tokenId - 1].isPainted = true;
    }