contract Normies is IERC721, Ownable, Functional {

    using Address for address;
    
    // Token name
    string private _name;

    // Token symbol
    string private _symbol;
    
    // URI Root Location for Json Files
    string private _baseURI;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;
    
    // Specific Functionality
    bool public mintActive;
    bool public whitelistActive;
    bool private _hideTokens;  //for URI redirects
    uint256 public price;
    uint256 public totalTokens;
    uint256 public numberMinted;
    uint256 public maxPerTxn;
    uint256 public whiteListMax;
    uint256 public WLprice;
    
    mapping(address => uint256) private _whitelist;

    //Distribution Wallets
    address Founder =       payable(0xD61344DBd5321C7583B1166705f993Ff126DACf8); //85%
    address Developer =     payable(0x2E07cd18E675c921E8c523E36D79788734E94f88); //5%
    address Consulting =    payable(0xe9A36d2d6820539ec2F3b4ddC68Fd337BF8Ce293); //5%
    address Community =     payable(0x9f4A549dD4415968f0279dB9Ae43AFfD7354CFDE); //5%

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor() {
        _name = "Paranormies";
        _symbol = "NORMIE";
        _baseURI = "https://paranormies.io/metadata/";
        _hideTokens = true;
        

        totalTokens = 9700;
        price = 69 * (10 ** 15); // Replace leading value with price in finney  0.069E
        WLprice = 69 * (10 ** 15);
        maxPerTxn = 20;
        whiteListMax = 4;
    }

    //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return  interfaceId == type(IERC721).interfaceId ||
                interfaceId == type(IERC721Metadata).interfaceId ||
                interfaceId == type(IERC165).interfaceId ||
                interfaceId == Normies.onERC721Received.selector;
    }
    
    // Standard Withdraw function for the owner to pull the contract
    function withdraw() external onlyOwner {
        uint256 Funds = address(this).balance;
        bool success;

        uint256 sendAmount = (Funds * 85) / 100;
        (success, ) = Founder.call{value: sendAmount}("");
        require(success, "Transaction Unsuccessful");
        
        sendAmount = (Funds * 5) / 100;
        (success, ) = Developer.call{value: sendAmount}("");
        require(success, "Transaction Unsuccessful"); 
        
        sendAmount = (Funds * 5) / 100;
        (success, ) = Consulting.call{value: sendAmount}("");
        require(success, "Transaction Unsuccessful");
        
        sendAmount = (Funds * 5) / 100;
        (success, ) = Community.call{value: sendAmount}("");
        require(success, "Transaction Unsuccessful");
        
    }
    
    function ownerMint(address _to, uint256 qty) external onlyOwner {
        require((numberMinted + qty) > numberMinted, "Math overflow error");
        require((numberMinted + qty) <= totalTokens, "Cannot fill order");
        
        uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
        
        for(uint256 i = 0; i < qty; i++) {
            _safeMint(_to, mintSeedValue + i);
            numberMinted ++;  //reservedTokens can be reset, numberMinted can not
        }
    }

    function singleAirdrop(address _to) external onlyOwner {
        require(numberMinted <= totalTokens, "Cannot Fill Order");

        uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch

        numberMinted ++;  //reservedTokens can be reset, numberMinted can not
        _safeMint(_to, mintSeedValue);
    }
    
    function airDrop(address[] memory _to) external onlyOwner {
        uint256 qty = _to.length;
        require((numberMinted + qty) > numberMinted, "Math overflow error");
        require((numberMinted + qty) <= totalTokens, "Cannot fill order");
        
        uint256 mintSeedValue = numberMinted;
        
        for(uint256 i = 0; i < qty; i++) {
            _safeMint(_to[i], mintSeedValue + i);
            numberMinted ++;  //reservedTokens can be reset, numberMinted can not
        }
    }
    
    function mintWL(uint256 qty) external payable reentryLock {
        require(whitelistActive, "WL not open");
        require(msg.value == qty * WLprice, "WL: Wrong Eth Amount");
        require((qty + numberMinted) <= totalTokens, "WL: Not enough avaialability");
        require(_whitelist[_msgSender()] >= qty, "WL: unauth amount");

        _whitelist[_msgSender()] -= qty;
        
        uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch

        //send tokens
        for(uint256 i = 0; i < qty; i++) {
            _safeMint(_msgSender(), mintSeedValue + i);
            numberMinted ++;
        }

    }

    function mint(uint256 qty) external payable reentryLock {
        require(mintActive, "mint not open");
        require(msg.value >= qty * price, "Mint: Insufficient Funds");
        require(qty <= maxPerTxn, "Mint: Above Trxn Threshold!");
        require((qty + numberMinted) <= totalTokens, "Mint: Not enough avaialability");
        
        uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch

        //send tokens
        for(uint256 i = 0; i < qty; i++) {
            _safeMint(_msgSender(), mintSeedValue + i);
            numberMinted ++;
        }
    }
    
    // allows holders to burn their own tokens if desired
    function burn(uint256 tokenID) external {
        require(_msgSender() == ownerOf(tokenID));
        _burn(tokenID);
    }
    
    //////////////////////////////////////////////////////////////
    //////////////////// Setters and Getters /////////////////////
    //////////////////////////////////////////////////////////////
    
    function whiteList(address account) external onlyOwner {
        _whitelist[account] = whiteListMax;
    }
    
    function whiteListMany(address[] memory accounts) external onlyOwner {
        for (uint256 i; i < accounts.length; i++) {
            _whitelist[accounts[i]] = whiteListMax;
        }
    }

    function checkWhitelist(address testAddress) external view returns (uint256) {
        return _whitelist[testAddress];
    }
    
    function setMaxMintThreshold(uint256 maxMints) external onlyOwner {
        maxPerTxn = maxMints;
    }
    
    function setWhitelistThreshold(uint whitelisterBuyLimit) external onlyOwner {
        whiteListMax = whitelisterBuyLimit;
    }
    
    function setBaseURI(string memory newURI) public onlyOwner {
        _baseURI = newURI;
    }
    
    function activateMint() public onlyOwner {
        mintActive = true;
    }
    
    function deactivateMint() public onlyOwner {
        mintActive = false;
    }

    function activateWL() public onlyOwner {
        whitelistActive = true;
    }
    
    function deactivateWL() public onlyOwner {
        whitelistActive = false;
    }
    
    function setPrice(uint256 newPrice) public onlyOwner {
        price = newPrice;
    }

    function setWhitelistPrice(uint256 newPrice) public onlyOwner {
        WLprice = newPrice;
    }

    function setTotalTokens(uint256 numTokens) public onlyOwner {
        totalTokens = numTokens;
    }

    function totalSupply() external view returns (uint256) {
        return numberMinted; //stupid bs for etherscan's call
    }
    
    function hideTokens() external onlyOwner {
        _hideTokens = true;
    }
    
    function revealTokens() external onlyOwner {
        _hideTokens = false;
    }
    
    function getBalance(address tokenAddress) view external returns (uint256) {
        //return _balances[tokenAddress]; //shows 0 on etherscan due to overflow error
        return _balances[tokenAddress] / (10**15); //temporary fix to report in finneys
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: bal qry for zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: own query nonexist tkn");
        return owner;
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ownerOf(tokenId);
        require(to != owner, "ERC721: approval current owner");

        require(
            msg.sender == owner || isApprovedForAll(owner, msg.sender),
            "ERC721: caller !owner/!approved"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved nonexistent tkn");
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        require(operator != msg.sender, "ERC721: approve to caller");

        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved");
        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @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.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "txfr to non ERC721Reciever");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: op query nonexistent tkn");
        address owner = ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "txfr to non ERC721Reciever"
        );
    }

    /**
     * @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 = 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(ownerOf(tokenId) == from, "ERC721: txfr token not owned");
        require(to != address(0), "ERC721: txfr to 0x0 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(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(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver(to).onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("txfr to non ERC721Reciever");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }
    
    // *********************** ERC721 Token Receiver **********************
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) {
        //InterfaceID=0x150b7a02
        return this.onERC721Received.selector;
    }

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

    // **************************************** Metadata Standard Functions **********
    //@dev Returns the token collection name.
    function name() external view returns (string memory){
        return _name;
    }

    //@dev Returns the token collection symbol.
    function symbol() external view returns (string memory){
        return _symbol;
    }

    //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
    function tokenURI(uint256 tokenId) external view returns (string memory){
        require(_exists(tokenId), "ERC721Metadata: URI 0x0 token");
        string memory tokenuri;
        
        if (_hideTokens) {
            //redirect to mystery box
            tokenuri = string(abi.encodePacked(_baseURI, "mystery.json"));
        } else {
            //Input flag data here to send to reveal URI
            tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json"));
        }
        
        return tokenuri;
    }
    
    function contractURI() public view returns (string memory) {
            return string(abi.encodePacked(_baseURI,"contract.json"));
    }
    // *******************************************************************************

    receive() external payable {}
    
    fallback() external payable {}
}
// ******************************************************************************************************************************
// **************************************************  Start of Main Contract ***************************************************
// ******************************************************************************************************************************
function tokenURI(uint256 tokenId) external view returns (string memory){
        require(_exists(tokenId), "ERC721Metadata: URI 0x0 token");
        string memory tokenuri;
        
        if (_hideTokens) {
            //redirect to mystery box
            tokenuri = string(abi.encodePacked(_baseURI, "mystery.json"));
        } else {
            //Input flag data here to send to reveal URI
            tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json"));
        }
        
        return tokenuri;
    }
//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.