contract TheCyborx is ERC721, Ownable {
    using SafeMath for uint256;
    using Strings for uint256;

    uint256 public startingIndexBlock;
    uint256 public startingIndex;
    uint256 public privateMintPrice = 0.08 ether;
    uint256 public publicMintPrice = 0.09 ether;
    uint256 public maxToMint = 20;
    uint256 public MAX_MINT_WHITELIST = 5;
    uint256 public MAX_ELEMENTS = 1000;
    uint256 public REVEAL_TIMESTAMP;

    bool public revealed = false;

    string public notRevealedUri = "";

    string public PROVENANCE_HASH = "";
    bool public saleIsActive = false;
    bool public privateSaleIsActive = true;

    struct Whitelist {
        address addr;
        uint256 claimAmount;
        uint256 hasMinted;
    }

    mapping(address => Whitelist) public whitelist;
    mapping(address => Whitelist) public winnerlist;

    address[] whitelistAddr;
    address[] winnerlistAddr;

    constructor(
        string memory _name,
        string memory _symbol,
        string memory _initBaseURI,
        string memory _initNotRevealedUri
    ) ERC721(_name, _symbol) {
        REVEAL_TIMESTAMP = block.timestamp;
        _setBaseURI(_initBaseURI);
        setNotRevealedURI(_initNotRevealedUri);
    }

    /**
     * Get the array of token for owner.
     */
    function tokensOfOwner(address _owner)
        external
        view
        returns (uint256[] memory)
    {
        uint256 tokenCount = balanceOf(_owner);
        if (tokenCount == 0) {
            return new uint256[](0);
        } else {
            uint256[] memory result = new uint256[](tokenCount);
            for (uint256 index; index < tokenCount; index++) {
                result[index] = tokenOfOwnerByIndex(_owner, index);
            }
            return result;
        }
    }

    /**
     * Check if certain token id is exists.
     */
    function exists(uint256 _tokenId) public view returns (bool) {
        return _exists(_tokenId);
    }

    /**
     * Set presell price to mint
     */
    function setPrivateMintPrice(uint256 _price) external onlyOwner {
        privateMintPrice = _price;
    }

    /**
     * Set publicsell price to mint
     */
    function setPublicMintPrice(uint256 _price) external onlyOwner {
        publicMintPrice = _price;
    }

    /**
     * Set maximum count to mint per once.
     */
    function setMaxToMint(uint256 _maxValue) external onlyOwner {
        maxToMint = _maxValue;
    }

    /**
     * reserve by owner
     */

    function reserve(uint256 _count) public onlyOwner {
        uint256 total = totalSupply();
        require(total + _count <= MAX_ELEMENTS, "Exceeded");
        for (uint256 i = 0; i < _count; i++) {
            _safeMint(msg.sender, total + i);
        }
    }

    /**
     * Set reveal timestamp when finished the sale.
     */
    function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner {
        REVEAL_TIMESTAMP = _revealTimeStamp;
    }

    /*
     * Set provenance once it's calculated
     */
    function setProvenanceHash(string memory _provenanceHash)
        external
        onlyOwner
    {
        PROVENANCE_HASH = _provenanceHash;
    }

    function setBaseURI(string memory baseURI) external onlyOwner {
        _setBaseURI(baseURI);
    }

    function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
        notRevealedUri = _notRevealedURI;
    }

    //only owner
    function reveal() public onlyOwner {
        revealed = true;
    }

    function tokenURI(uint256 tokenId)
        public
        view
        virtual
        override
        returns (string memory)
    {
        require(
            _exists(tokenId),
            "ERC721Metadata: URI query for nonexistent token"
        );
        require(tokenId <= totalSupply(), "URI query for nonexistent token");
        if (revealed == false) {
            return notRevealedUri;
        }
        string memory base = baseURI();
        return string(abi.encodePacked(base, "/", tokenId.toString(), ".json"));
    }

    /*
     * Pause sale if active, make active if paused
     */

    function flipSaleState() public onlyOwner {
        saleIsActive = !saleIsActive;
    }

    function flipPrivateSaleState() public onlyOwner {
        privateSaleIsActive = !privateSaleIsActive;
    }

    /**
     * Mints tokens
     */
    function mint(uint256 _count) public payable {
        uint256 total = totalSupply();
        require(saleIsActive, "Sale must be active to mint");
        require((total + _count) <= MAX_ELEMENTS, "Max limit");

        if (privateSaleIsActive) {
            require(
                (privateMintPrice * _count) <= msg.value,
                "Value below price"
            );
            require(_count <= MAX_MINT_WHITELIST, "Above max tx count");
            require(isWhitelisted(msg.sender), "Is not whitelisted");
            require(
                whitelist[msg.sender].hasMinted.add(_count) <=
                    MAX_MINT_WHITELIST,
                "Can only mint 5 while whitelisted"
            );
            whitelist[msg.sender].hasMinted = whitelist[msg.sender]
                .hasMinted
                .add(_count);
        } else {
            if (isWhitelisted(msg.sender)) {
                require((balanceOf(msg.sender) - whitelist[msg.sender].hasMinted + _count) <= maxToMint, "Can only mint 20 tokens");
            } else {
                require((balanceOf(msg.sender) + _count) <= maxToMint, "Can only mint 20 tokens");
            }
            require(
                (publicMintPrice * _count) <= msg.value,
                "Value below price"
            );
        }

        for (uint256 i = 0; i < _count; i++) {
            uint256 mintIndex = totalSupply() + 1;
            if (totalSupply() < MAX_ELEMENTS) {
                _safeMint(msg.sender, mintIndex);
            }
        }

        // If we haven't set the starting index and this is either
        // 1) the last saleable token or
        // 2) the first token to be sold after the end of pre-sale, set the starting index block
        if (
            startingIndexBlock == 0 &&
            (totalSupply() == MAX_ELEMENTS ||
                block.timestamp >= REVEAL_TIMESTAMP)
        ) {
            startingIndexBlock = block.number;
        }
    }

    function freeMint(uint256 _count) public {
        uint256 total = totalSupply();
        require(isWinnerlisted(msg.sender), "Is not winnerlisted");
        require(saleIsActive, "Sale must be active to mint");
        require((total + _count) <= MAX_ELEMENTS, "Exceeds max supply");
        require(
            winnerlist[msg.sender].claimAmount > 0,
            "You have no amount to claim"
        );
        require(
            _count <= winnerlist[msg.sender].claimAmount,
            "You claim amount exceeded"
        );

        for (uint256 i = 0; i < _count; i++) {
            uint256 mintIndex = totalSupply() + 1;
            if (totalSupply() < MAX_ELEMENTS) {
                _safeMint(msg.sender, mintIndex);
            }
        }

        winnerlist[msg.sender].claimAmount =
            winnerlist[msg.sender].claimAmount -
            _count;

        // If we haven't set the starting index and this is either
        // 1) the last saleable token or
        // 2) the first token to be sold after the end of pre-sale, set the starting index block
        if (
            startingIndexBlock == 0 &&
            (totalSupply() == MAX_ELEMENTS ||
                block.timestamp >= REVEAL_TIMESTAMP)
        ) {
            startingIndexBlock = block.number;
        }
    }

    /**
     * Set the starting index for the collection
     */
    function setStartingIndex() external onlyOwner {
        require(startingIndex == 0, "Starting index is already set");
        require(startingIndexBlock != 0, "Starting index block must be set");

        startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_ELEMENTS;
        // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
        if ((block.number - startingIndexBlock) > 255) {
            startingIndex = uint256(blockhash(block.number - 1)) % MAX_ELEMENTS;
        }
        // Prevent default sequence
        if (startingIndex == 0) {
            startingIndex = startingIndex + 1;
        }
    }

    function setWhitelistAddr(address[] memory addrs) public onlyOwner {
        whitelistAddr = addrs;
        for (uint256 i = 0; i < whitelistAddr.length; i++) {
            addAddressToWhitelist(whitelistAddr[i]);
        }
    }

    /**
     * Set the starting index block for the collection, essentially unblocking
     * setting starting index
     */
    function emergencySetStartingIndexBlock() external onlyOwner {
        require(startingIndex == 0, "Starting index is already set");

        startingIndexBlock = block.number;
    }

    function withdraw() public onlyOwner {
        uint256 balance = address(this).balance;
        (bool success, ) = msg.sender.call{value: balance}("");
        require(success);
    }

    function partialWithdraw(uint256 _amount, address payable _to)
        external
        onlyOwner
    {
        require(_amount > 0, "Withdraw must be greater than 0");
        require(_amount <= address(this).balance, "Amount too high");
        (bool success, ) = _to.call{value: _amount}("");
        require(success);
    }

    function addAddressToWhitelist(address addr)
        public
        onlyOwner
        returns (bool success)
    {
        require(!isWhitelisted(addr), "Already whitelisted");
        whitelist[addr].addr = addr;
        success = true;
    }

    function isWhitelisted(address addr)
        public
        view
        returns (bool isWhiteListed)
    {
        return whitelist[addr].addr == addr;
    }

    function addAddressToWinnerlist(address addr, uint256 claimAmount)
        public
        onlyOwner
        returns (bool success)
    {
        require(!isWinnerlisted(addr), "Already winnerlisted");
        winnerlist[addr].addr = addr;
        winnerlist[addr].claimAmount = claimAmount;
        winnerlist[addr].hasMinted = 0;
        success = true;
    }

    function isWinnerlisted(address addr)
        public
        view
        returns (bool isWinnerListed)
    {
        return winnerlist[addr].addr == addr;
    }
}
/**
 * @title TheCyborx contract
 * @dev Extends ERC721 Non-Fungible Token Standard basic implementation
 */
function setStartingIndex() external onlyOwner {
    require(startingIndex == 0, "Starting index is already set");
    require(startingIndexBlock != 0, "Starting index block must be set");

    startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_ELEMENTS;
    // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
    if ((block.number - startingIndexBlock) > 255) {
        startingIndex = uint256(blockhash(block.number - 1)) % MAX_ELEMENTS;
    }
    // Prevent default sequence
    if (startingIndex == 0) {
        startingIndex = startingIndex + 1;
    }
}

/**
 * Set the starting index for the collection
 */