// Contract: GlobalGoats
// Target function: function transfergg(uint256 tokenId) external payable
 to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}









/**
 * @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();
    }
}




//Global Goats Main Contract

contract GlobalGoats is ERC721Enumerable, Ownable {

    using SafeMath for uint256;
    using Strings for uint256;

    uint256 public constant collection_Supply = 2323;

    uint256 public constant MAX_PURCHASE = 20;

    uint256 public constant MAX_MintedForPromotion = 25;

    uint256 public goatsMintedForPromotion;

    uint256 public preSaleGoatsMinted;

    uint256 public constant MAX_MintedGoldenGoats = 100;

    uint256 public constant MAX_PreSaleMintedGoats = 350;

    uint256 public constant PRICE_PER_GOAT = 150000000000000000 wei;  //0.15 ETH

    uint256 public constant PreSale_PRICE_PER_GOAT = 110000000000000000 wei;  //0.11 ETH

    bool private _saleIsActive;

    mapping(uint256 => uint256) private _tokenPriceWei;

    mapping (uint256 => address) private _tokenListOwner;

    bool private _preSaleIsActive;

    string private _metaBaseUri = "https://assets.globalgoats.io/";


//Index of Golden Goats
    uint[] GoldenGoats = [283, 107, 44, 344, 9, 23, 40, 218, 349, 165, 74, 2, 19, 227, 215, 315, 4, 303, 237, 209, 27, 199, 336, 256, 280, 312, 7, 317, 89, 169, 37, 204, 144, 133, 342, 156, 201, 196, 101, 164, 265, 275, 173, 228, 79, 277, 41, 292, 230, 337, 1619, 480, 1551, 1400, 1678, 1658, 2222, 1461, 2323, 2125, 981, 1639, 712, 1230, 1645, 1083, 976, 2244, 939, 786, 1223, 2022, 585, 2261, 926, 1985, 893, 1571, 1098, 792, 1944, 1754, 1352, 821, 1771, 931, 2018, 432, 1901, 1919, 867, 1295, 1697, 667, 2175, 1926, 1100, 1166, 1978, 2085];

    uint[] getOnSale;
    //Alternative Option 
    struct GoldenGoat {
        address userAddress;
        uint tokenId;
    }
    

    constructor() ERC721("GlobalGoats", "GOAT") {

        _saleIsActive = true;
        _preSaleIsActive = true;
        goatsMintedForPromotion = 0;
    }

    //public mint
    function mint(uint16 numberOfTokens) public payable {
        require(saleIsActive(), "Sale is not active");
        require(numberOfTokens <= MAX_PURCHASE, "Can only mint max 20 tokens per transaction");
        require(PRICE_PER_GOAT.mul(numberOfTokens) == msg.value, "Ether value sent is incorrect.Need 0.15 ETH for each GOAT");
        require(totalSupply() < collection_Supply, "collection sold out");
        require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");

        _mintTokens(numberOfTokens,msg.sender);

    }

    //Pre-Sale Mint
    function preSalemint(uint16 numberOfTokens) public payable {
        require(saleIsActive(), "Sale is not active");
        require(numberOfTokens <= MAX_PURCHASE, "Can only mint max 20 tokens per transaction");
        require(preSaleGoatsMinted.add(numberOfTokens) <= MAX_PreSaleMintedGoats, "Cannot mint more Pre-sale mintgoats for promotion");
        require(PreSale_PRICE_PER_GOAT.mul(numberOfTokens) == msg.value, "Ether value sent is incorrect.Need 0.11 ETH For Presale for each GOAT");
        require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");
        preSaleGoatsMinted += numberOfTokens;

        _mintTokens(numberOfTokens,msg.sender);

    }


    /* Owner functions */

    /**
     * Reserve a few Goats e.g. for giveaways
     */
    function reserveMint(uint16 numberOfTokens , address _to) external onlyOwner {
        require(goatsMintedForPromotion.add(numberOfTokens) <= MAX_MintedForPromotion, "Cannot mint more goats for promotion");
        require(totalSupply().add(numberOfTokens) < collection_Supply, "Insufficient supply");
        goatsMintedForPromotion += numberOfTokens;
        _mintTokens(numberOfTokens,_to);
    }

    
    function setSaleIsActive(bool active) external onlyOwner {
        _saleIsActive = active;
    }

    function setPreSaleIsActive(bool active) external onlyOwner {
        _preSaleIsActive = active;
    }


    function setMetaBaseURI(string memory baseURI) external onlyOwner {
        _metaBaseUri = baseURI;
    }

    function withdraw(uint256 amount) external onlyOwner {
        require(amount <= address(this).balance, 'Insufficient balance');
        payable(msg.sender).transfer(amount);
    }

    function withdrawAll() external onlyOwner {
        payable(msg.sender).transfer(address(this).balance);
    }

    /* View functions */
    function saleIsActive() public view returns(bool) {
        return _saleIsActive;
    }

    function presaleIsActive() public view returns(bool) {
        return _preSaleIsActive;
    }
    //get array of golden goats TokenIds
    function _getGGTokens() external view returns(uint[] memory) {

        uint[] memory goats = new uint[](GoldenGoats.length);
        
        for (uint j = 0; j < GoldenGoats.length; j++) {
        
            goats[j] = GoldenGoats[j];
        }

        return goats;
    }


 function _getOnSalePlatformTokens() external view returns(uint[] memory) {

        uint[] memory goats = new uint[](getOnSale.length);
        uint256 tokenId;

        for (uint j = 0; j < getOnSale.length; j++) {
            tokenId = getOnSale[j];
        if (_exists(tokenId)) {
        address listowneraddress = _tokenListOwner[tokenId];
        address currentOnweraddress = ownerOf(tokenId);

         if( listowneraddress == currentOnweraddress) {   // if else statement
         goats[j] = getOnSale[j];
         } 
        }
        }

        return goats;
    }


    function IsGGToken(uint256 tokenId) public view returns(bool status) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        status = false;
        for (uint l = 0; l < GoldenGoats.length; l++) {
            
            if (GoldenGoats[l] == tokenId) {
                status = true;
                break;
            }
        }
         return status;

    }

 function IsonSaleToken(uint256 tokenId) public view returns(bool status) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        status = false;
        for (uint k = 0; k < getOnSale.length; k++) {
            if (getOnSale[k] == tokenId) {
                status = true;
                break;
            }
        }
        return status;

    }


    function getCurrentPriceOfToken(uint256 tokenId) public view virtual returns(uint256) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(_tokenListOwner[tokenId] == ownerOf(tokenId) , "Not For Sale Currently on GlobalGoats.io");
        uint256 Price = _tokenPriceWei[tokenId];

        return Price;
    }

    function tokenURI(uint256 tokenId) override public view returns(string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
        return string(abi.encodePacked(_baseURI(), "tokens/", uint256(tokenId).toString(), "/metadata.json"));
    }

    /* Internal functions */
    function _mintTokens(uint16 numberOfTokens , address _to) internal {
        for (uint16 i = 0; i < numberOfTokens; i++) {
            uint256 tokenId = totalSupply() + 1;
            //uint256 tokenId = _tokenIdTracker.current();
            _safeMint(_to, tokenId);
        }
    }


    function approve(uint256 _tokenId, address _from) internal virtual {
        require(ownerOf(_tokenId) == msg.sender, "NOT OWNER");
        isApprovedForAll(_from, address(this));
    }


    //send Price in wei
    function _setTokenPrice(uint256 tokenId, uint256 tokenPrice) external  {
        require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _tokenPriceWei[tokenId] = tokenPrice;
        getOnSale.push(tokenId);
        _tokenListOwner[tokenId] = msg.sender;
        approve(tokenId, msg.sender);

    }