// Contract: emLoot
// Target function: function encode(bytes memory data) internal pure returns (string memory)
Index}.
     */
    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, food 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 emLoot is ERC721Enumerable, ReentrancyGuard, Ownable {
    string[] private face = [
        unicode'😀',
        unicode'😂',
        unicode'😍',
        unicode'😎',
        unicode'😡',
        unicode'🥺',
        unicode'😩',
        unicode'😴',
        unicode'😷',
        unicode'😈',
        unicode'👻',
        unicode'🤖',
        unicode'🤮',
        unicode'😱',
        unicode'😭',
        unicode'🤪',
        unicode'🤡',
        unicode'👽'
    ];

    string[] private pet = [
        unicode'🐶',
        unicode'🐱',
        unicode'🐭',
        unicode'🐰',
        unicode'🦊',
        unicode'🐻',
        unicode'🐯',
        unicode'🦁',
        unicode'🐮',
        unicode'🐷',
        unicode'🐸',
        unicode'🐵',
        unicode'🐔',
        unicode'🦉',
        unicode'🦄',
        unicode'🐟',
        unicode'🐳',
        unicode'🐏'
    ];

    string[] private food = [
        unicode'🍳',
        unicode'🍔',
        unicode'🍕',
        unicode'🍣',
        unicode'🍵',
        unicode'🍺',
        unicode'🍎',
        unicode'🍉',
        unicode'🍒',
        unicode'🍋',
        unicode'🍌',
        unicode'🍜',
        unicode'🍭',
        unicode'🍼',
        unicode'🦴',
        unicode'🧋',
        unicode'🎂',
        unicode'🧀'
    ];

    string[] private sport = [
        unicode'⚽️',
        unicode'🏀',
        unicode'🏈',
        unicode'🎾',
        unicode'🏐',
        unicode'🎱',
        unicode'🏓',
        unicode'🏸',
        unicode'🏒',
        unicode'⛳️',
        unicode'🏹',
        unicode'🎣',
        unicode'🥊',
        unicode'🤿',
        unicode'🥋',
        unicode'⛷',
        unicode'🏊️',
        unicode'🚴️'
    ];

    string[] private traffic = [
        unicode'🚗',
        unicode'🚕',
        unicode'🚌',
        unicode'🚜',
        unicode'🛴',
        unicode'🦽',
        unicode'🚲',
        unicode'🛵',
        unicode'🚄',
        unicode'✈️',
        unicode'🚀',
        unicode'⛵️',
        unicode'🚁',
        unicode'🦵'
    ];

    string[] private job = [
        unicode'👮',
        unicode'👷',
        unicode'🧑‍💻',
        unicode'🧑‍🎓',
        unicode'🧑‍🌾',
        unicode'🧑‍🎨',
        unicode'🧑‍🔬',
        unicode'🧑‍🏫',
        unicode'🧑‍🍳',
        unicode'🧑‍⚕️',
        unicode'🕵️',
        unicode'🧑‍🚒',
        unicode'🧑‍🚀',
        unicode'🥷',
        unicode'🧞️',
        unicode'🧛'
    ];

    string[] private tool = [
        unicode'💊',
        unicode'📱',
        unicode'💻',
        unicode'🎙',
        unicode'🎥',
        unicode'🛠',
        unicode'🔪',
        unicode'⛓',
        unicode'💣',
        unicode'🔫',
        unicode'🚽',
        unicode'🎁',
        unicode'🎉',
        unicode'💎',
        unicode'💰'
    ];

    string[] private attitude = [
        unicode'👍',
        unicode'👎',
        unicode'✊',
        unicode'🤘',
        unicode'🤏',
        unicode'🤙',
        unicode'🙏',
        unicode'🖕',
        unicode'👌',
        unicode'👏',
        unicode'💩',
        unicode'👄',
        unicode'👋',
        unicode'✌️',
        unicode'💪'
    ];

    string[] private suffixes = [
        unicode'at 🌅',
        unicode'at 🌄',
        unicode'at 🎆',
        unicode'at 🏞',
        unicode'at 🌃',
        unicode'at 🏦',
        unicode'at 🏥',
        unicode'at 🏠',
        unicode'at 🎡',
        unicode'at 🏖',
        unicode'at 🏛'
    ];

    string[] private namePrefixes = [
        unicode'🔥',
        unicode'🌈',
        unicode'⭐️',
        unicode'🌎',
        unicode'❤️',
        unicode'💡',
        unicode'💯'
    ];

    string[] private nameSuffixes = [
        unicode'❗️',
        unicode'❓',
        unicode'🎉',
        unicode'💎',
        unicode'💰',
        unicode'🎖'
    ];

    function random(string memory input) internal pure returns (uint256) {
        return uint256(keccak256(abi.encodePacked(input)));
    }

    function getFace(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'FACE', face);
    }

    function getPet(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'PET', pet);
    }

    function getFood(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'FOOD', food);
    }

    function getSport(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'SPORT', sport);
    }

    function getTraffic(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'TRAFFIC', traffic);
    }

    function getJob(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'JOB', job);
    }

    function getTool(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'TOOL', tool);
    }

    function getAttitude(uint256 tokenId) public view returns (string memory) {
        return pluck(tokenId, 'ATTITUDE', attitude);
    }

    function pluck(
        uint256 tokenId,
        string memory keyPrefix,
        string[] memory sourceArray
    ) internal view returns (string memory) {
        uint256 rand = random(
            string(abi.encodePacked(keyPrefix, toString(tokenId)))
        );
        string memory output = sourceArray[rand % sourceArray.length];
        uint256 greatness = rand % 21;
        if (greatness > 14) {
            output = string(
                abi.encodePacked(output, ' ', suffixes[rand % suffixes.length])
            );
        }
        if (greatness >= 19) {
            string[2] memory name;
            name[0] = namePrefixes[rand % namePrefixes.length];
            name[1] = nameSuffixes[rand % nameSuffixes.length];
            if (greatness == 19) {
                output = string(
                    abi.encodePacked(
                        '#',
                        name[0],
                        ' ',
                        name[1],
                        '# ',
                        output,
                        unicode' 🏆'
                    )
                );
            } else {
                output = string(
                    abi.encodePacked('#', name[0], ' ', name[1], '# ', output)
                );
            }
        }
        return output;
    }

    function tokenURI(uint256 tokenId)
        public
        view
        override
        returns (string memory)
    {
        string[17] memory parts;
        parts[
            0
        ] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';

        parts[1] = getFace(tokenId);

        parts[2] = '</text><text x="10" y="40" class="base">';

        parts[3] = getPet(tokenId);

        parts[4] = '</text><text x="10" y="60" class="base">';

        parts[5] = getFood(tokenId);

        parts[6] = '</text><text x="10" y="80" class="base">';

        parts[7] = getSport(tokenId);

        parts[8] = '</text><text x="10" y="100" class="base">';

        parts[9] = getTraffic(tokenId);

        parts[10] = '</text><text x="10" y="120" class="base">';

        parts[11] = getJob(tokenId);

        parts[12] = '</text><text x="10" y="140" class="base">';

        parts[13] = getTool(tokenId);

        parts[14] = '</text><text x="10" y="160" class="base">';

        parts[15] = getAttitude(tokenId);

        parts[16] = '</text></svg>';

        string memory output = string(
            abi.encodePacked(
                parts[0],
                parts[1],
                parts[2],
                parts[3],
                parts[4],
                parts[5],
                parts[6],
                parts[7],
                parts[8]
            )
        );
        output = string(
            abi.encodePacked(
                output,
                parts[9],
                parts[10],
                parts[11],
                parts[12],
                parts[13],
                parts[14],
                parts[15],
                parts[16]
            )
        );

        string memory json = Base64.encode(
            bytes(
                string(
                    abi.encodePacked(
                        '{"name": "Person #',
                        toString(tokenId),
                        '", "description": "Emoji Loot uses emoji to describe an abstract person", "image": "data:image/svg+xml;base64,',
                        Base64.encode(bytes(output)),
                        '","attributes": [',
                        abi.encodePacked(
                            '{"trait_type": "Face", "value": "',
                            parts[1],
                            '"},',
                            '{"trait_type": "Pet", "value": "',
                            parts[3],
                            '"},',
                            '{"trait_type": "Food", "value": "',
                            parts[5],
                            '"},'
                        ),
                        abi.encodePacked(
                            '{"trait_type": "Sport", "value": "',
                            parts[7],
                            '"},',
                            '{"trait_type": "Traffic", "value": "',
                            parts[9],
                            '"},',
                            '{"trait_type": "Job", "value": "',
                            parts[11],
                            '"},'
                        ),
                        abi.encodePacked(
                            '{"trait_type": "Tool", "value": "',
                            parts[13],
                            '"},',
                            '{"trait_type": "Attitude", "value": "',
                            parts[15],
                            '"}'
                        ),
                        ']}'
                    )
                )
            )
        );
        output = string(
            abi.encodePacked('data:application/json;base64,', json)
        );

        return output;
    }

    function claim(uint256 tokenId) public nonReentrant {
        require(tokenId > 0 && tokenId < 7778, 'Token ID invalid');
        _safeMint(_msgSender(), tokenId);
    }

    function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
        require(tokenId > 7777 && tokenId < 8001, 'Token ID invalid');
        _safeMint(owner(), tokenId);
    }

    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT license
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return '0';
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    constructor() ERC721('emLoot', 'emLoot') Ownable() {}
}

library Base64 {
    bytes internal constant TABLE =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';